在学习前后端分离项目时,解决开发环境的跨域问题。 特此记录一下
基本用法
mmodule.exports = {
devServer: {
proxy: {
'/sign': 'http://localhost:8081'
}
}
};
//当请求 /sign/xxx 就会被代理到 http://localhost:8081/sign/xxx,
//例如 /sign/user 现在会被代理到请求 http://localhost:8081/sign/user
如果不希望传递/sign,则如下配置
mmodule.exports = {
devServer: {
proxy: {
'/sign': {
target: 'http://localhost:8081',
pathRewrite: {'^/api',''}
}
}
}
};
//当请求 /sign/xxx 就会被代理到 http://localhost:8081/xxx,
//例如 /sign/user 现在会被代理到请求 http://localhost:8081/user
默认情况下,不接受HTTPS上运行且认证且证书无效的后端服务器。如果需要,设置secure:false
mmodule.exports = {
devServer: {
proxy: {
'/sign': {
target: 'http://localhost:8081',
secure: false
}
}
}
};
如果想将多个特定路径代理到同一个目标,则可以使用一个或多个带有context
属性的对象的数组
module.exports = {
devServer: {
proxy: [
{
context: ['/auth', '/api'],
target: 'http://localhost:8081',
},
],
},
};
当进行代理时,Host 头部的源默认会保持原状;你可以设置 changeOrigin 为 true 来覆盖这种行为。
假如后端地址为http://localhost:3000
,前端为http://localhost:3001
,如果设置changeOrigin:true
那么后端通过request.getHeader(“Host”)获取的地址将是http://localhost:3000
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
}
}
}
};
当没有设置changeOrigin
时:
设置了changeOrigin:true
具体原因的话,我也是个小白。所以抱歉了我也不知道🥲
对于浏览器请求,你想要提供一个 HTML 页面,但是对于 API 请求则保持代理。可以通过请求头中的Accept属性来配置。
module.exports = {
//...
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
bypass: function(req, res, proxyOptions) {
if (req.headers.accept.indexOf('html') !== -1) {
return '/edit.html';
}
}
}
}
}
};
上面代码中:如果请求头中的Accept属性中包含html则会转发到当前目录下的edit.html
页面。
代理多个不同的路径
module.exports = {
devServer: {
proxy: {
'/api/action': {
target: 'http://192.191.1.3',
changeOrigin: true,
ws: true,
secure: false
},
'/api': {
target: 'http://192.191.1.2',
changeOrigin: true,
ws: true,
secure: false
},
}
}
};
注意:匹配多个的时候要将匹配范围最小的放在最前面。
vue-cli和vite配置和webpack的代理配置大致一样,但是vite的不是devServer.proxy
是server.proxy