Node.js配合node-http-proxy解決本地開發(fā)ajax跨域問題
情景:
前后端分離,本地前端開發(fā)調(diào)用接口會有跨域問題,一般有以下3種解決方法:
1. 后端接口打包到本地運行(缺點:每次后端更新都要去測試服下一個更新包,還要在本地搭建java運行環(huán)境,麻煩)
2. CORS跨域:后端接口在返回的時候,在header中加入'Access-Control-Allow-origin':* 之類的(有的時候后端不方便這樣處理,前端就蛋疼了)
3. 用nodejs搭建本地http服務器,并且判斷訪問接口URL時進行轉(zhuǎn)發(fā),完美解決本地開發(fā)時候的跨域問題。
用到的技術(shù):
1. nodejs搭建本地http服務器
2. 應用node-http-proxy,做接口url的轉(zhuǎn)發(fā)
具體方法:
1. node.js搭建本地http服務器參考了shawn.xie的《nodejs搭建本地http服務器》
2. node.js做轉(zhuǎn)發(fā)使用node-http-proxy實現(xiàn),官方文檔:https://github.com/nodejitsu/node-http-proxy#using-https
3. 操作方法參考了:http://hao.jser.com/archive/10394/?utm_source=tuicool&utm_medium=referral
4. 下面是我自己的實戰(zhàn)操作
項目準備
1. npm初始化
npm init
2. 安裝node-http-proxy模塊
npm install http-proxy --save-dev
3. 項目結(jié)構(gòu)
下面的例子中,我們把html文件直接放在根目錄'./',也可以指定一個網(wǎng)站目錄,在proxy.js中可以自定義
配置HTTP服務器和PROXY轉(zhuǎn)發(fā)
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轉(zhuǎn)發(fā) 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
可以看到項目中調(diào)用的http://localhost:3000/..... 都會從http://192.168.10.38:8180/...... 獲取數(shù)據(jù),然后轉(zhuǎn)發(fā)到本地。
這樣就不存在跨域了。
以上所述是小編給大家介紹的Node.js配合node-http-proxy解決本地開發(fā)ajax跨域問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
利用node.js+mongodb如何搭建一個簡單登錄注冊的功能詳解
這篇文章主要給大家介紹了關(guān)于利用node.js+mongodb如何搭建一個簡單登錄注冊功能的相關(guān)資料,文中通過示例代碼介紹非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面跟著小編來一起學習學習吧。2017-07-07nodejs npm錯誤Error:UNKNOWN:unknown error,mkdir ''D:\Develop\n
今天小編就為大家分享一篇關(guān)于nodejs npm錯誤Error:UNKNOWN:unknown error,mkdir 'D:\Develop\nodejs\node_global'at Error,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03解決koa2 ctx.render is not a function報錯問題
這篇文章主要介紹了解決koa2 ctx.render is not a function報錯問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08nodejs 提示‘xxx’ 不是內(nèi)部或外部命令解決方法
本文介紹了node.js包管理工具npm安裝模塊后,無法通過命令行執(zhí)行命令,提示‘xxx’ 不是內(nèi)部或外部命令的解決方法,給需要的小伙伴參考下。2014-11-11