標籤:
情景:
前後端分離,本地前端開發調用介面會有跨域問題,一般有以下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跨域問題