文章目录
脚手架配置代理
方法一
在vue.config.js中添加如下配置
devServer: {
proxy: "url"
}
说明:
- 优点:配置简单,请求资源时直接发给前端(url)即可。
- 缺点:不能配置多个代理,不能灵活控制请求是否走代理。
- 工作方式:当前前端中不存在资源时,请求才会转发给服务器。不然就会请求当前前端。
方法二
编写vue.config.js配置的具体规则:
module.exports = defineConfig({
devServer: {
proxy: {
// 请求前缀,匹配所有以'/api'开头的请求路径
'/api': {
target: 'http://localhost:5000', // 代理目标基础服务器
pathRewrite: {
'^/api': ''}, // 将发个服务器的请求,取消前缀
ws: true, // 用于支持websocket
changeOrigin: false // 用于控制请求头中的host字段 默认true,如果设置为true,服务器收到的请求头的host为:localhost:5000;设置为false时,host为:localhost:当前的前端启动端口
},
'/carapi': {
target: 'http://localhost:5001',
pathRewrite: {
'^/carapi': ''},
// ws: true, // 用于支持websocket
// changeOrigin: false // 用于控制请求头中的host字段 默认true
}
/* '/foo': {
target: '<other_url>'
} */
}
}
})
说明:
- 优点:可以配置多个代理,且可以灵活的控制请求是否走代理
- 缺点:配置比较繁琐,请求是必须添加前缀
vue.config.js
const {
defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false, //关闭语法检查
// 开启代理服务器,方式一: 本地public 中有的资源不会转发,只能配置一个代理
/* devServer: {
proxy: 'http://localhost:5000'
} */
devServer: {
proxy: {
// 请求前缀
'/api': {
target: 'http://localhost:5000',
pathRewrite: {
'^/api': ''},
ws: true, // 用于支持websocket
changeOrigin: false // 用于控制请求头中的host字段 默认true
},
'/carapi': {
target: 'http://localhost:5001',
pathRewrite: {
'^/carapi': ''},
// ws: true, // 用于支持websocket
// changeOrigin: false // 用于控制请求头中的host字段 默认true
}
/* '/foo': {
target: '<other_url>'
} */
}
}
})
App.vue
<template>