爱玩科技网
您的当前位置:首页说说如何利用 Node.js 代理解决跨域问题

说说如何利用 Node.js 代理解决跨域问题

来源:爱玩科技网


2 配置

我们以知乎日报为例,配置两个代理。一个代理内容,另一个代理图片。

在项目根目录,配置 proxy.js :

//代理
const http = require('http');
const request = require('request');

const hostIp = '127.0.0.1';
const apiPort = 8070;
const imgPort = 8071;

//创建 API 代理服务
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', '*');
 //返回代理内容
 res.end(body);
 }
 }

 request.get(options, callback);
});

//监听 API 端口
apiServer.listen(apiPort, hostIp, () => {
 console.log('代理接口,运行于 http://' + hostIp + ':' + apiPort + '/');
});

//创建图片代理服务
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);


});

//监听图片端口
imgServer.listen(imgPort, hostIp, () => {
 console.log('代理图片,运行于 http://' + hostIp + ':' + imgPort + '/')
});

代理的关键点是在响应头添加 Access-Control-Allow-Origin 为 *,表示允许所有域进行访问。

代理前地址 代理后地址
https://pic2.zhimg.com/v2-bb0a0282fd9bddaa245af4de9dcc45.jpg http://127.0.0.1:8071/img/v2-bb0a0282fd9bddaa245af4de9dcc45.jpg
http://news-at.zhihu.com/story/9710345 http://127.0.0.1:8070/9710345

3. 运行

执行:

node proxy.js

 运行结果:

代理接口,运行于 http://127.0.0.1:8070/代理图片,运行于http://127.0.0.1:8071/

打开浏览器,输入代理后的地址,就可以正常访问啦O(∩_∩)O哈哈~

代理内容:

代理图片:

以上所述是小编给大家介绍的Node.js代理解决跨域问题详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

显示全文