当前位置: 移动技术网 > IT编程>脚本编程>NodeJs > 说说如何利用 Node.js 代理解决跨域问题

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

前后端分离,经常会出现跨域访问被限制的问题。

跨域访问限制是服务端出于安全考虑的限制行为。即只有同域或者指定域的请求,才能访问。这样还可以防止图片被盗链。服务端(比如 node.js)可以通过代理,来解决这一问题。

1 安装 request 库

npm install request --save-dev

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-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. 运行

执行:

node proxy.js

 运行结果:

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

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

代理内容:

代理图片:

以上所述是小编给大家介绍的node.js代理解决跨域问题详解整合,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网