配置代理 – 下载第三方库axios
打开vue2官网 => 生态系统 => Vue Cli => 配置参考 =>devServer.proxy(开发者服务器)
参考链接:https://cli.vuejs.org/zh/config/#devserver-proxy
解释:
如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服务器。这个问题可以通过 vue.config.js 中的 devServer.proxy 选项来配置。
方式一 – 只能配置一个代理
//页面需要发请求的地方的写法
import axios from 'axios'
axios.get('http://localhost:8080/students).....
在vue.config.js 中的 devServer.proxy 选项来配置
module.exports = {
devServer: {
proxy: 'http://localhost:5000'
}
}
方式二 – 建议使用
//页面需要发请求的地方的写法
import axios from 'axios'
axios.get('http://localhost:8080/api/students).....
在vue.config.js 中的 devServer.proxy 选项来配置
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:5000',
pathRewrite:{'^/api':''},
ws: true, // 用于支持websocket
changeOrigin: true
},
//另外一个代理
'/foo': {
target: 'http://localhost:5001'
}
}
}
}