介绍
这篇文章给大家分享的是有关怎样利用节点。js代理解决跨域问题的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
前后端分离,经常会出现跨域访问被限制的问题。
跨域访问限制是服务端出于安全考虑的限制行为。即只有同域或者指定域的请求,才能访问。这样还可以防止图片被盗链。服务端(比如节点。js)可以通过代理,来解决这一问题。
<强> 1安装请求库强>
npm安装请求——save-dev
引用><强> 2配置强>
我们以知乎日报为例,配置两个代理。一个代理内容,另一个代理图片。
在项目根目录,配置代理。js:
//代理 const http =,要求(& # 39;http # 39;); const request =,要求(& # 39;请求# 39;); const hostIp =, & # 39; 127.0.0.1 # 39;; const apiPort =, 8070; const imgPort =, 8071;//创建,API 代理服务 const apiServer =, http.createServer((点播,res),=祝辞,{ console.log才能(& # 39;[apiServer] req.url=& # 39; + req.url); const 才能;url =, & # 39; http://news-at.zhihu.com/story& # 39;, +, req.url; console.log才能(& # 39;[apiServer] url=& # 39; + url); const 才能;options =, { ,,,url: url ,,}; function 才能;回调(错误,,反应,身体),{ ,,,if (! error ,,, response.statusCode ===, 200), { ,,,,,//编码类型 ,,,,,res.setHeader(& # 39;内容类型# 39;,,& # 39;文本/平原;charset=utf - 8 # 39;); ,,,,,//允许跨域 ,,,,,res.setHeader (& # 39; Access-Control-Allow-Origin& # 39;,, & # 39; * & # 39;); ,,,,,//返回代理内容 ,,,,,res.end(身体); ,,,} ,,} request.get才能(选项,,回调); });//监听,API 端口 apiServer.listen (apiPort, hostIp,,(),=祝辞,{ console.log才能(& # 39;代理接口,运行于,http://& # 39;, +, hostIp +, & # 39;: & # 39;, +, apiPort +, & # 39;/& # 39;); });//创建图片代理服务 const imgServer =, http.createServer((点播,res),=祝辞,{ const 才能;url =, & # 39; https://pic2.zhimg.com/& # 39;, + req.url.split (& # 39;/img/& # 39;) [1]; console.log才能(& # 39;[imgServer] url=& # 39;, +, url); const 才能;options =, { ,,,url:,网址, ,,,编码:零 ,,}; function 才能;回调(错误,,反应,身体),{ ,,,if (! error ,,, response.statusCode ===, 200), { ,,,,,const contentType =, response.headers[& # 39;内容类型# 39;]; ,,,,,res.setHeader(& # 39;内容类型# 39;,,contentType); ,,,,,res.setHeader (& # 39; Access-Control-Allow-Origin& # 39;,, & # 39; * & # 39;); ,,,,,res.end(身体); ,,,} ,,} request.get才能(选项,,回调); });//监听图片端口 imgServer.listen (imgPort, hostIp,,(),=祝辞,{ console.log才能(& # 39;代理图片,运行于,http://& # 39;, +, hostIp +, & # 39;: & # 39;, +, imgPort +, & # 39;/& # 39;) });代理的关键点是在响应头添加Access-Control-Allow-Origin为*,表示允许所有域进行访问。
代理前地址代理后地址https://pic2.zhimg.com/v2-bb0a0282fd989bddaa245af4de9dcc45.jpghttp://127.0.0.1:8071/img/v2-bb0a0282fd989bddaa245af4de9dcc45.jpghttp://news-at.zhihu.com/story/9710345http://127.0.0.1:8070/9710345<强> 3。运行强>
执行:
节点proxy.js
引用>,运行结果:
代理接口,运行于http://127.0.0.1:8070代理图片,运行于http://127.0.0.1:8071
打开浏览器,输入代理后的地址,就可以正常访问啦O (∩_∩) O哈哈~
代理内容:
代理图片:
感谢各位的阅读!关于“怎样利用node . js代理解决跨域问题”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
怎样利用node . js代理解决跨域问题