Vue 中的代理服务器配置
Vue
的代理配置可以在 vue.config.js
文件中进行设置。可以使用 devServer
选项来配置代理。
1、普通代理
module.exports = {
devServer: {
proxy: {
"/api": "http://localhost:3000",
},
},
};
现在,对 /api/users
的请求会将转发到 http://localhost:3000/api/users
。
2、重写路径
module.exports = {
devServer: {
proxy: {
"/api": {
target: "http://localhost:3000",
pathRewrite: {
"^/api": "",
},
},
},
},
};
将以 /api
开头的请求代理到 http://localhost:3000
。 pathRewrite
选项用于重写请求路径,将 /api
去掉。这样,对 /api/user
请求将被转发到 http://localhost:3000/user
。
3、安全控制
默认情况下,将不接受在 HTTPS
上运行且证书无效的后端服务器。 如果需要,可以这样修改配置:
module.exports = {
devServer: {
proxy: {
"/api": {
target: "https://other-server.example.com",
secure: false, // 使用的是http协议则设置为false,https协议则设置为true
},
},
},
};
4、代理绕过
有时不想代理所有内容。 可以基于函数的返回值绕过代理。
在该功能中,可以访问请求 (req)
,响应 (res)
和代理选项 (proxyOptions)
。
- 返回
null
或undefined
以继续使用代理处理请求。 - 返回
false
会为请求产生404
错误。 - 返回提供服务的路径,而不是继续代理请求。
例如。 对于浏览器请求,想要提供 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";
}
},
},
},
},
};
5、批量代理
如果想将多个特定路径代理到同一目标,则可以使用一个或多个带有 context
属性的对象的数组:
module.exports = {
devServer: {
proxy: [
{
context: ["/auth", "/api"],
target: "http://localhost:3000",
},
],
},
};
6、修改 Host
默认情况下,代理时会保留主机头的来源,可以将 changeOrigin
设置为 true
以覆盖此行为。如果设置成 true
:发送请求头中 Host
会设置成 target
。
module.exports = {
devServer: {
proxy: {
"/api": {
target: "http://localhost:3000",
changeOrigin: true,
},
},
},
};
7、显示真实地址
当我们使用代理后想要确认现在用的接口是不是我希望代理的服务下的接口,按照老规矩就是直接按下 f12 进入浏览器的开发者工具,我们会发现 Network 找的的接口链接的地址还是原来没有代理的地址,难道没有代理成功吗?其实代理已经生效了,只是浏览器这边不会直接给你放出代理后的地址,这是如果还是不放心,可以添加一个 logLevel
参数,并且设置为 debug
,这样你再刷新,就会发现显示的地址就是我们代理后的地址。
module.exports = {
devServer: {
proxy: {
"/api": {
target: "http://localhost:3000",
changeOrigin: true,
logLevel: "debug", // 显示代理后的真实地址
},
},
},
};