vue项目中,前端与后台进行数据请求或者提交的时候,如果后台没有设置跨域,前端本地调试代码的时候就会报“No 'Access-Control-Allow-Origin' header is present on the requested resource.” 这种跨域错误。
使用http-proxy-middleware 代理解决(项目使用vue-cli脚手架搭建)
打开config/index.js,在proxyTable中添写如下代码:
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/****** 支持跨域 **/
proxyTable:{
'/api':{//匹配所以‘api’开头的请求路径
target:'http://localhost:4000',//代理目标的基础路径
changeOrigin:true,//支持跨域
pathRewrite:{//重写路径:去掉路径开头的'/api'
'^/api':''
// '^/api':'http://localhost:4000'//重写路径
}
}
},
使用axios请求数据时直接使用“/api”:
getData () {
axios.get('/api/user.json', function (res) {
console.log(res)
})
通过这中方法去解决跨域,打包部署时还按这种方法会出问题。解决方法如下:
let serverUrl = '/api/' //本地调试时
// let serverUrl = 'http://ceshi.com/' //打包部署上线时
export default {
dataUrl: serverUrl + 'user.json'
}