在vue.config.js
配置文件中加上devServer
配置项
proxy里面的’/demo’是进入代理服务器的标识,target
要请求的跨域路径,pathRewrite
是访问路径的时候将路径标识删除
module.exports = {pages: {index: {//入口entry: 'src/main.js',},},lintOnSave:false, //关闭语法检查//开启代理服务器(方式一)/* devServer: {proxy: 'http://localhost:5000'}, *///开启代理服务器(方式二)devServer: {proxy: {'/demo': {target: 'http://localhost:5001',pathRewrite:{'^/demo':''},// ws: true, //用于支持websocket// changeOrigin: true //用于控制请求头中的host值}}}}
在需要访问跨域请求的ajax访问地址加上进入代理服务器的标识demo就能实现跨域请求了
methods: {getCars(){axios.get('http://localhost:8080/demo/cars').then(response => {console.log('请求成功了',response.data)},error => {console.log('请求失败了',error.message)})}},
如果觉得《Vue-cli配置代理服务器 解决跨域请求问题》对你有帮助,请点赞、收藏,并留下你的观点哦!