webpack - devServer - proxy
webpack - devServer - proxy
target
proxy: {
'/api': {
target: 'http: //localhost:3000'
}
}
| 请求地址 | 代理后地址 |
|---|---|
| /api/users | http://localhost:3000/api/users |
pathRewrite
如果你不想始终传递 /api ,则需要重写路径:
proxy: {
'/api': {
target: 'http: //localhost:3000',
pathRewrite: {'^/api' : '' }
}
}
| pathRewrite | 请求地址 | 代理后地址 |
|---|---|---|
| /api/users | http://localhost:3000/users | |
| /api/users | http://localhost:3000/xyz/users |
url 含 http是否会代理
// proxy
proxy: {
'/proxy': {
target: 'http: //localhost:7777/dev-api',
pathRewrite: {'^/proxy' : '' }
}
// ===
// '/proxy': {
// target: 'http: //localhost:7777',
// pathRewrite: {'^/proxy' : '/dev-api'
// }
// }
},
| 请求地址 | 代理后地址 | status |
|---|---|---|
| /proxy | http: //localhost:7777/dev-api | 200 |
| http://localhost:7777/proxy/ | http: //localhost:7777/dev-api | 200 |
| http://localhost:7777/proxy1/ | http: //localhost:7777/dev-api1 | 404 |
| http://localhost:7778/proxy/ | http: //localhost:7778/dev-api | failed |
^key
// proxy
proxy: {
'^/proxy': {
target: 'http: //localhost:7777/dev-api',
pathRewrite: {'^/proxy' : '' }
}
},
| 请求地址 | 代理后地址 | status |
|---|---|---|
| http://localhost:7777/proxy/ | http: //localhost:7777/dev-api | 200 |
| http://localhost:7777/proxy1/ | http: //localhost:7777/dev-api1 | 404 |
| http://localhost:7778/proxy/ | http: //localhost:7778/dev-api | failed |
无效证书的后端服务器 secure
默认情况下,不接受运行在 HTTPS 上,且使用了无效证书的后端服务器。如果你想要接受,修改配置如下
module.exports = {
//...
devServer: {
proxy: {
'/api': {
target: 'https://other-server.example.com',
secure: false
}
}
}
};
过滤/绕过代理 bypass
有时你不想代理所有的请求。可以基于一个函数的返回值绕过代理。
在函数中你可以访问请求体、响应体和代理选项。必须返回 false 或路径,来跳过代理请求。
例如:对于浏览器请求,你想要提供一个 HTML 页面,但是对于 API 请求则保持代理。你可以这样做:
module.exports = {
//...
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
bypass: function(req, res, proxyOptions) {
if (req.headers.accept.indexOf('html') !== -1) {
console.log('Skipping proxy for browser request.');
return '/index.html';
}
}
}
}
}
};
多个路径特定到同一个 target
想要代理多个路径特定到同一个 target 下,你可以使用由一个或多个「具有 context 属性的对象」构成的数组:
module.exports = {
//...
devServer: {
proxy: [{
context: ['/auth', '/api'],
target: 'http://localhost:3000',
}]
}
};
根代理
默认情况下,根请求不会被代理。要启用根代理,应该将 devServer.index 选项指定为 falsy 值:
module.exports = {
//...
devServer: {
index: '', // specify to enable root proxying
host: '...',
contentBase: '...',
proxy: {
context: () => true,
target: 'http://localhost:1234'
}
}
};
changeOrigin
默认情况下,代理时会保留主机标头的原点,您可以将changeOrigin设置为true以覆盖此行为。它在某些情况下很有用,例如使用基于名称的虚拟托管站点。
module.exports = {
//...
devServer: {
proxy: {
'/api': 'http://localhost:3000',
changeOrigin: true
}
}
};
Lee2

浙公网安备 33010602011771号