webpack.config.js
module.exports = {
// ...
devServer: {
proxy: {
'/api': 'http://localhost:3000'
}
}
}
对路径 /api/users
的请求将会被代理到 http://localhost:3000/api/users
。
如果不希望传递 /api
,可以进行重写路径:
webpack.config.js
module.exports = {
// ...
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
pathRewrite: {
'^/api': ''
}
}
}
}
}
所有以/api
开头的路径请求都将被拦截掉。
如果希望请求 /api/user.json
的路径代理到 /api/demo.json
:
module.export = {
// ...
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
pathRewrite: {
'user.json': 'demo.json'
}
}
}
}
}
默认情况下,将不接受在 HTTPS 上运行且证书无效的后端服务器。如果需要可以如下配置:
webpack.config.js
module.export = {
// ...
devServer: {
proxy: {
'/api': {
target: 'https://other-server.example.com',
secure: false
}
}
}
}
有时不想代理所有内容,可以基于函数的返回值绕过代理。
在该项功能中,可以访问请求,响应和代理选项。
-
返回
null
或underfuned
以继续使用代理处理请求。 -
返回 false 会为请求产生 404 错误。
-
返回提供服务的路径,而不是继续代理请求。
例如:对于浏览器请求,想要提供 HTML 页面,但是对于 API 请求,想要代理它,可以执行以下操作:
webpack.config.js
module.export = {
// ...
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'
}
}
}
}
}
}
如果想将多个特定路径代理到同一个目标,则可以使用一个活多个带有 context
属性的对象的数组:
webpack.config.js
module.export = {
// ...
devServer: {
proxy: [
{
context: ['/auth', '/api'],
target: 'http://localhost:3000'
}
]
}
}
注意:默认情况下不会代理对root根路径的请求,如果需要启用根路径的代理,应将 index
选项指定为false 或者 空 ‘ ’