-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevServer.config.js
More file actions
89 lines (86 loc) · 2.88 KB
/
devServer.config.js
File metadata and controls
89 lines (86 loc) · 2.88 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
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
// 不同浏览器存放cookie的对象
const cookieMap = {};
// 去掉域名的sso登录地址
const loginUrl = '/login';
// 默认打开页,为空时写'/'
const openPage = '/';
// 设置cookie
const setCookie = (userAgent, cookies) => {
let map = cookieMap[userAgent] || {};
cookies.forEach((cookie) => {
let [string, key, value] = cookie.match(/^(.*?)=(.*?);/);
map[key] = value;
});
cookieMap[userAgent] = map;
}
// 获取cookie
const getCookie = (userAgent) => {
let map = cookieMap[userAgent] || {};
let cookie = '';
for(let key in map) {
cookie += `${key}=${map[key]};`
}
return cookie;
}
module.exports = {
// index值为空时,可以让devServer拦截首页(localhost:xxxx),配合 context: ['/'] 使用
index: '',
// 自动打开页面
open: true,
// 代理配置
proxy: [{
// 代理服务器的请求
context: ['/api'],
// 服务器的目标地址
target: "http://api.example.com",
changeOrigin: true,
// 监听代理请求
onProxyReq(proxyReq, req, res) {
// proxyReq是node服务器发给api服务器的response
// req是浏览器发给node服务器的request
// res是node服务器返回给浏览器的response
// 将cookie插入到请求头
proxyReq.setHeader('Cookie', getCookie(req.get('User-Agent')));
},
// 监听代理返回
onProxyRes(proxyRes, req, res) {
// proxyRes是登录服务器返回给node服务器的response
// req是浏览器发给node服务器的request
// res是node服务器返回给浏览器的response
// 如果响应头中含有set-cookie字段,则将其cookie存入内存中
if(proxyRes.headers['set-cookie']) {
setCookie(req.get('User-Agent'), proxyRes.headers['set-cookie']);
}
}
}, {
// 代理登录相关的所有请求
context: ['/login'],
// 登录的目标地址
target: "http://sso.example.com",
changeOrigin: true,
// 监听代理返回
onProxyRes(proxyRes, req, res) {
// proxyRes是登录服务器返回给node服务器的response
// req是浏览器发给node服务器的request
// res是node服务器返回给浏览器的response
// 如果响应头中含有set-cookie字段,则将其cookie存入内存中
if(proxyRes.headers['set-cookie']) {
setCookie(req.get('User-Agent'), proxyRes.headers['set-cookie']);
}
// 如果响应头为重定向,则将重定向地址指向我们需要的页面
if(proxyRes.statusCode === 302) {
proxyRes.headers['Location'] = openPage;
}
}
}, {
// 拦截首页(localhost:xxxx)
context: ['/'],
bypass: function(req, res, proxyOptions) {
// 如果请求为首页且发起该请求的浏览器没有登录,则跳转到登录页
if (req.url === '/' && !cookieMap[req.get('User-Agent')]) {
res.redirect(loginUrl);
return true;
}
}
}]
}