Node.js配合node-http-proxy解決本地開發(fā)ajax跨域問(wèn)題
情景:
前后端分離,本地前端開發(fā)調(diào)用接口會(huì)有跨域問(wèn)題,一般有以下3種解決方法:
1. 后端接口打包到本地運(yùn)行(缺點(diǎn):每次后端更新都要去測(cè)試服下一個(gè)更新包,還要在本地搭建java運(yùn)行環(huán)境,麻煩)
2. CORS跨域:后端接口在返回的時(shí)候,在header中加入'Access-Control-Allow-origin':* 之類的(有的時(shí)候后端不方便這樣處理,前端就蛋疼了)
3. 用nodejs搭建本地http服務(wù)器,并且判斷訪問(wèn)接口URL時(shí)進(jìn)行轉(zhuǎn)發(fā),完美解決本地開發(fā)時(shí)候的跨域問(wèn)題。
用到的技術(shù):
1. nodejs搭建本地http服務(wù)器
2. 應(yīng)用node-http-proxy,做接口url的轉(zhuǎn)發(fā)
具體方法:
1. node.js搭建本地http服務(wù)器參考了shawn.xie的《nodejs搭建本地http服務(wù)器》
2. node.js做轉(zhuǎn)發(fā)使用node-http-proxy實(shí)現(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. 下面是我自己的實(shí)戰(zhàn)操作
項(xiàng)目準(zhǔn)備
1. npm初始化
npm init
2. 安裝node-http-proxy模塊
npm install http-proxy --save-dev
3. 項(xiàng)目結(jié)構(gòu)
下面的例子中,我們把html文件直接放在根目錄'./',也可以指定一個(gè)網(wǎng)站目錄,在proxy.js中可以自定義
配置HTTP服務(wù)器和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/', //接口地址 // 下面的設(shè)置用于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'; //判斷如果是接口訪問(wèn),則通過(guò)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的源碼,補(bǔ)充了幾個(gè)字體文件的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" };
以上就是全部源碼
然后把項(xiàng)目中的接口地址改成http://localhost:3000/......
啟動(dòng)nodejs服務(wù)
啟動(dòng)cmd,定位到項(xiàng)目目錄,運(yùn)行
node proxy.js
訪問(wèn):
http://localhost:3000/index.html
可以看到項(xiàng)目中調(diào)用的http://localhost:3000/..... 都會(huì)從http://192.168.10.38:8180/...... 獲取數(shù)據(jù),然后轉(zhuǎn)發(fā)到本地。
這樣就不存在跨域了。
以上所述是小編給大家介紹的Node.js配合node-http-proxy解決本地開發(fā)ajax跨域問(wèn)題,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
- node.js+jQuery實(shí)現(xiàn)用戶登錄注冊(cè)AJAX交互
- Node.js如何響應(yīng)Ajax的POST請(qǐng)求并且保存為JSON文件詳解
- Node.js獲取前端ajax提交的request信息
- Node.js服務(wù)器環(huán)境下使用Mock.js攔截AJAX請(qǐng)求的教程
- node.js+Ajax實(shí)現(xiàn)獲取HTTP服務(wù)器返回?cái)?shù)據(jù)
- node.js chat程序如何實(shí)現(xiàn)Ajax long-polling長(zhǎng)鏈接刷新模式
- Ajax異步文件上傳與NodeJS express服務(wù)端處理
- Ajax 的初步實(shí)現(xiàn)(使用vscode+node.js+express框架)
相關(guān)文章
利用node.js+mongodb如何搭建一個(gè)簡(jiǎn)單登錄注冊(cè)的功能詳解
這篇文章主要給大家介紹了關(guān)于利用node.js+mongodb如何搭建一個(gè)簡(jiǎn)單登錄注冊(cè)功能的相關(guān)資料,文中通過(guò)示例代碼介紹非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面跟著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-07-07nodejs npm錯(cuò)誤Error:UNKNOWN:unknown error,mkdir ''D:\Develop\n
今天小編就為大家分享一篇關(guān)于nodejs npm錯(cuò)誤Error:UNKNOWN:unknown error,mkdir 'D:\Develop\nodejs\node_global'at Error,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-03-03解決koa2 ctx.render is not a function報(bào)錯(cuò)問(wèn)題
這篇文章主要介紹了解決koa2 ctx.render is not a function報(bào)錯(cuò)問(wèn)題,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08說(shuō)說(shuō)node中的可讀流和可寫流的區(qū)別
這篇文章主要介紹了說(shuō)說(shuō)node中的可讀流和可寫流的區(qū)別,詳細(xì)的介紹了可讀流和可寫流,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-06-06nodejs 提示‘xxx’ 不是內(nèi)部或外部命令解決方法
本文介紹了node.js包管理工具npm安裝模塊后,無(wú)法通過(guò)命令行執(zhí)行命令,提示‘xxx’ 不是內(nèi)部或外部命令的解決方法,給需要的小伙伴參考下。2014-11-11