内容简介:前后端分离,经常会出现跨域访问被限制的问题。跨域访问限制是服务端出于安全考虑的限制行为。即只有同域或者指定域的请求,才能访问。这样还可以防止图片被盗链。服务端(比如 Node.js)可以通过代理,来解决这一问题。我们以知乎日报为例,配置两个代理。一个代理内容,另一个代理图片。
前后端分离,经常会出现跨域访问被限制的问题。
跨域访问限制是服务端出于安全考虑的限制行为。即只有同域或者指定域的请求,才能访问。这样还可以防止图片被盗链。服务端(比如 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 |
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Hatching Twitter
Nick Bilton / Portfolio Hardcover / 2013-11-5 / USD 28.95
The dramatic, unlikely story behind the founding of Twitter, by New York Times bestselling author and Vanity Fair special correspondent The San Francisco-based technology company Twitter has become......一起来看看 《Hatching Twitter》 这本书的介绍吧!