情景:
前后端分離,本地前端開發調用接口會有跨域問題,一般有以下3種解決方法:
1. 后端接口打包到本地運行(缺點:每次后端更新都要去測試服下一個更新包,還要在本地搭建java運行環境,麻煩)
2. CORS跨域:后端接口在返回的時候,在header中加入'Access-Control-Allow-origin':* 之類的(有的時候后端不方便這樣處理,前端就蛋疼了)
3. 用nodejs搭建本地http服務器,并且判斷訪問接口URL時進行轉發,完美解決本地開發時候的跨域問題。
用到的技術:
1. nodejs搭建本地http服務器
2. 應用node-http-proxy,做接口url的轉發
具體方法:
1. node.js搭建本地http服務器參考了shawn.xie的《nodejs搭建本地http服務器》
2. node.js做轉發使用node-http-proxy實現,官方文檔:https://github.com/nodejitsu/node-http-proxy#using-https
3. 操作方法參考了:http://hao.jser.com/archive/10394/?utm_source=tuicool&utm_medium=referral
4. 下面是我自己的實戰操作
項目準備
1. npm初始化
npm init
2. 安裝node-http-proxy模塊
npm install http-proxy --save-dev
3. 項目結構

下面的例子中,我們把html文件直接放在根目錄'./',也可以指定一個網站目錄,在proxy.js中可以自定義
配置HTTP服務器和PROXY轉發
var PORT = 3000;var http = require('http');var url=require('url');var fs=require('fs');var mine=require('./mine').types;var path=require('path');var httpProxy = require('http-proxy');var proxy = httpProxy.createProxyServer({target: 'http://192.168.10.38:8180/', //接口地址// 下面的設置用于https// ssl: {// key: fs.readFileSync('server_decrypt.key', 'utf8'),// cert: fs.readFileSync('server.crt', 'utf8')// },// secure: false});proxy.on('error', function(err, req, res){res.writeHead(500, {'content-type': 'text/plain'});console.log(err);res.end('Something went wrong. And we are reporting a custom error message.');});var server = http.createServer(function (request, response) {var pathname = url.parse(request.url).pathname;//var realPath = path.join("main-pages", pathname); // 指定根目錄var realPath = path.join("./", pathname);console.log(pathname);console.log(realPath);var ext = path.extname(realPath);ext = ext ? ext.slice(1) : 'unknown';//判斷如果是接口訪問,則通過proxy轉發if(pathname.indexOf("mspj-mall-admin") > 0){proxy.web(request, response);return;}fs.exists(realPath, function (exists) {if (!exists) {response.writeHead(404, {'Content-Type': 'text/plain'});response.write("This request URL " + pathname + " was not found on this server.");response.end();} else {fs.readFile(realPath, "binary", function (err, file) {if (err) {response.writeHead(500, {'Content-Type': 'text/plain'});response.end(err);} else {var contentType = mine[ext] || "text/plain";response.writeHead(200, {'Content-Type': contentType});response.write(file, "binary");response.end();}});}});});server.listen(PORT);console.log("Server runing at port: " + PORT + ".");MINE.JS
這里參考shawn.xie的源碼,補充了幾個字體文件的mime。
exports.types = {"css": "text/css","gif": "image/gif","html": "text/html","ico": "image/x-icon","jpeg": "image/jpeg","jpg": "image/jpeg","js": "text/javascript","json": "application/json","pdf": "application/pdf","png": "image/png","svg": "image/svg+xml","swf": "application/x-shockwave-flash","tiff": "image/tiff","txt": "text/plain","wav": "audio/x-wav","wma": "audio/x-ms-wma","wmv": "video/x-ms-wmv","xml": "text/xml","woff": "application/x-woff","woff2": "application/x-woff2","tff": "application/x-font-truetype","otf": "application/x-font-opentype","eot": "application/vnd.ms-fontobject"};以上就是全部源碼
然后把項目中的接口地址改成http://localhost:3000/......
啟動nodejs服務
啟動cmd,定位到項目目錄,運行
node proxy.js
訪問:
http://localhost:3000/index.html
可以看到項目中調用的http://localhost:3000/..... 都會從http://192.168.10.38:8180/...... 獲取數據,然后轉發到本地。
這樣就不存在跨域了。
以上所述是小編給大家介紹的Node.js配合node-http-proxy解決本地開發ajax跨域問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答