前后端分離,經(jīng)常會(huì)出現(xiàn)跨域訪問被限制的問題。
跨域訪問限制是服務(wù)端出于安全考慮的限制行為。即只有同域或者指定域的請求,才能訪問。這樣還可以防止圖片被盜鏈。服務(wù)端(比如 Node.js)可以通過代理,來解決這一問題。
1 安裝 request 庫
npm install request --save-dev
2 配置
我們以知乎日報(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 = 'https://pic2.zhimg.com/' +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)行訪問。
| 代理前地址 | 代理后地址 |
|---|---|
| https://pic2.zhimg.com/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)容:

代理圖片:

以上所述是小編給大家介紹的Node.js代理解決跨域問題詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對VeVb武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答