-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.js
More file actions
52 lines (48 loc) · 1.6 KB
/
proxy.js
File metadata and controls
52 lines (48 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const http = require('http');
const request = require('request');
const hostname = '127.0.0.1';
const port = 8010;
const imgPort = 8011;
// 创建一个 API 代理服务
const apiServer = http.createServer((req, res) => {
const url = 'https://api.douban.com/v2' + req.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);
});
// 监听 8010 端口
apiServer.listen(port, hostname, () => {
console.log(`接口代理运行在 http://${hostname}:${port}/`);
});
// 创建一个图片代理服务
const imgServer = http.createServer((req, res) => {
const url = req.url.split('/img/')[1];
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);
});
// 监听 8011 端口
imgServer.listen(imgPort, hostname, () => {
console.log(`图片代理运行在 http://${hostname}:${imgPort}/`);
});