在vue项目开发时,需要请求后端,通常就会出现跨域问题。有2种常用的解决方案:
1、后端设置允许跨域访问
2、前端通过代理进行访问后端
这里用的是前端代理方法:
vue- ciI4是没有build文件夹跟config文件夹,所有的配置都在Vue.config.js完成。
vue-cli2.X跨域配置一般都在config中的index.js配置。
vue-cli3跨域配置同vue- ciI4
在项目根目录下创建vue.config.js文件
module.exports = {
// 配置跨域代理
devServer: {
// Paths
host: 'localhost',
port: '8080',
https: false,
open: true,
proxy: {
'/api': { // 匹配所有以 '/api'开头的请求路径
target: 'http://api.baidu.com', // 代理目标的基础路径
changeOrigin: true, // 支持跨域
pathRewrite: {// 重写路径: 去掉路径中开头的'/api'
'^/api': ''
}
},
"/main": {
target: 'http://api.bbs.com',
ws: true,
changOrigin: true,
pathRewrite: {
"^/main": ""
}
},
},
}
}
在项目页面直接使用
axios({
method: "post",
url: "/main/CustMessageFlow/add",
data: {
},
headers: {
"Content-Type": "application/json"
}
})
.then(res => {
console.log(res);
})