前后端分离,经常会出现跨域访问被限制的问题。
跨域访问限制是服务端出于安全考虑的限制行为。即只有同域或者指定域的请求,才能访问。这样还可以防止图片被盗链。服务端(比如 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 = 'http://img2.jintiankansha.me/get2?src=http://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 为
*
,表示允许所有域进行访问。
代理前地址 | 代理后地址 |
---|---|
http://img2.jintiankansha.me/get2?src=http://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哈哈~
代理内容:
代理图片: