-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
99 lines (76 loc) · 2.54 KB
/
server.js
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var http = require('http');
var argv = require('yargs').argv;
const request = require('request');
const url = require('url');
// 默认监听端口
var port = 8900;
// 可设置不同端口
if (argv.p) {
port = +argv.p;
}
http.createServer(function(req, res) {
// res.end('Hello World\n');
var urlObj = url.parse(req.url, true);
// console.log(urlObj);
var pathname = urlObj.pathname;
if (pathname.indexOf('/api') === 0) {
// 实际调用的api名称
var realApi = pathname.substr(4);
// 获取Origin请求头, 这里应该大写的O,
// 不过node下请求头全是小写的, 应该是作了封装
let origin = req.headers['origin'];
switch (realApi) {
case '/get1':
res.end('get1 success');
break;
case '/get2':
res.setHeader('Access-Control-Allow-Origin', '*');
res.end('get2 success');
break;
case '/get3':
// res.end('get3 success');
res.end(urlObj.query.callback + '(' + '"get3 success"' + ')');
break;
// 动态添加Access-Control-Allow-Origin头
case '/get4':
// 需要的才加
// 这里用正则判断是test.com或者xx.test.com的形式都允许跨域访问
if (origin && /^https?:\/\/(?:\w+\.)?test\.com.*$/.test(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
}
res.end('get4 success');
break;
// 带cookie
case '/get5':
// 需要的才加
// 这里用正则判断是test.com或者xx.test.com的形式都允许跨域访问
if (origin && /^https?:\/\/(?:\w+\.)?test\.com.*$/.test(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
}
// let cookies = req.headers['cookie'];
// console.log(cookies);
res.end('get5 success');
break;
// 代理接口
case '/proxy':
let query = urlObj.query,
method = req.method.toUpperCase(),
// 区分出来目标地址
target = query.__target;
delete query.__target;
if (origin && /^https?:\/\/(?:\w+\.)?test\.com.*$/.test(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
}
request({
url: target,
qs: query
}).pipe(res);
break;
default:
console.log('default: ', urlObj);
res.end(JSON.stringify(urlObj));
}
}
}).listen(port)
console.log('Server running at http://127.0.0.1:' + port);