新聞中心
這篇文章給大家分享的是有關(guān)怎樣利用 Node.js代理解決跨域問題的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
我們提供的服務(wù)有:成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)、微信公眾號(hào)開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、龍城ssl等。為超過千家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的龍城網(wǎng)站制作公司
前后端分離,經(jīng)常會(huì)出現(xiàn)跨域訪問被限制的問題。
跨域訪問限制是服務(wù)端出于安全考慮的限制行為。即只有同域或者指定域的請(qǐng)求,才能訪問。這樣還可以防止圖片被盜鏈。服務(wù)端(比如 Node.js)可以通過代理,來解決這一問題。
1 安裝 request 庫(kù)
npm install request --save-dev
2 配置
我們以知乎日?qǐng)?bào)為例,配置兩個(gè)代理。一個(gè)代理內(nèi)容,另一個(gè)代理圖片。
在項(xiàng)目根目錄,配置 proxy.js :
//代理 const http = require('http'); const request = require('request'); const hostIp = '127.0.0.1'; const apiPort = 8070; const imgPort = 8071; //創(chuàng)建 API 代理服務(wù) const apiServer = http.createServer((req, res) => { console.log('[apiServer]req.url='+req.url); const url = 'http://news-at.zhihu.com/story' + req.url; console.log('[apiServer]url='+url); const options = { url: url }; function callback(error, response, body) { if (!error && response.statusCode === 200) { //編碼類型 res.setHeader('Content-Type', 'text/plain;charset=UTF-8'); //允許跨域 res.setHeader('Access-Control-Allow-Origin', '*'); //返回代理內(nèi)容 res.end(body); } } request.get(options, callback); }); //監(jiān)聽 API 端口 apiServer.listen(apiPort, hostIp, () => { console.log('代理接口,運(yùn)行于 http://' + hostIp + ':' + apiPort + '/'); }); //創(chuàng)建圖片代理服務(wù) const imgServer = http.createServer((req, res) => { const url = '/upload/otherpic52/' +req.url.split('/img/')[1]; console.log('[imgServer]url=' + url); const options = { url: url, encoding: null }; function callback(error, response, body) { if (!error && response.statusCode === 200) { const contentType = response.headers['content-type']; res.setHeader('Content-Type', contentType); res.setHeader('Access-Control-Allow-Origin', '*'); res.end(body); } } request.get(options, callback); }); //監(jiān)聽圖片端口 imgServer.listen(imgPort, hostIp, () => { console.log('代理圖片,運(yùn)行于 http://' + hostIp + ':' + imgPort + '/') });
代理的關(guān)鍵點(diǎn)是在響應(yīng)頭添加 Access-Control-Allow-Origin 為 *,表示允許所有域進(jìn)行訪問。
代理前地址 | 代理后地址 |
---|---|
/upload/otherpic52/v2-bb0a0282fd989bddaa245af4de9dcc45.jpg | http://127.0.0.1:8071/img/v2-bb0a0282fd989bddaa245af4de9dcc45.jpg |
http://news-at.zhihu.com/story/9710345 | http://127.0.0.1:8070/9710345 |
3. 運(yùn)行
執(zhí)行:
node proxy.js
運(yùn)行結(jié)果:
代理接口,運(yùn)行于 http://127.0.0.1:8070/代理圖片,運(yùn)行于http://127.0.0.1:8071/
打開瀏覽器,輸入代理后的地址,就可以正常訪問啦O(∩_∩)O哈哈~
代理內(nèi)容:
代理圖片:
感謝各位的閱讀!關(guān)于“怎樣利用 Node.js代理解決跨域問題”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
分享標(biāo)題:怎樣利用Node.js代理解決跨域問題
URL分享:http://ef60e0e.cn/article/gsssoo.html