今天我们来谈谈如何在vue项目中实现跨域
这是我简单写的一个前端和一个后端
后端用的python的flask,运行在5000端口,代码如下:

下面是前端得一个代码,我们在home组件的mounted里去访问这个5000端口:

我的vue项目运行的端口是8080,和我的后端不是一个端口,如果访问的话,必定会报跨域的错:

那如果想解决跨域的问题,那就可以对vue进行配置,写一个代理
我们在项目更目录,新建vue.config.js

这边附上代码:
module.exports = {
configureWebpack: {
resolve: {
alias: {
'assets': '@/assets',
'components': '@/components',
'views': '@/views',
'utils':'@/utils'
}
}
},
devServer: {
overlay: { // 让浏览器 overlay 同时显示警告和错误
warnings: true,
errors: true
},
host: "localhost",
port: 8080, // 端口号
https: false, // https:{type:Boolean}
open: true, //配置自动启动浏览器
hotOnly: true, // 热更新
proxy: {
'/api': { //api代替target
target: 'http://localhost:5000/python',
changeOrigin: true,
ws: true,
pathRewrite: {
"^/api":""
}
}
}
}
}
然后前端页面的请求变成这样:
mounted(){
http.fetchGet("/api/vue-cli4").then((response) => {
console.log(response)
})
console.log("当前环境变量:"+process.env.NODE_ENV)
console.log("当前环境路径:"+process.env.VUE_APP_URL)
}
我们就可以拿到数据了。
