API地址:
http://www.caiji.me/api/test (本地开发的接口地址,访问接口会返回字符串“接口测试”;
axios请求方法:引入组件 axios后,编写请求接口方法:
mounted() {
axios.get('http://www.caiji.me/api').then(function (res) {
console.log(res);
});
}
本地 http://localhost:8080/ 运行项目时,在执行到请求时报错显示:
Access to XMLHttpRequest at 'http://www.caiji.me/api' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

很明显,属于跨域问题。此处不探讨其他解决方案。
下面说一下自己的解决方案。
本人初学vue脚手架版本为4.4.6 ,在vue.config.js 添加如下标红代码:
module.exports = {
outputDir: '../public'
, devServer: {
proxy: {
'/api': {
target: 'http://www.caiji.me',
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api': '/api',
}
}
}
}
}
同时将vue中请求修改为:
axios.get('/api/test').then(function (res) {
console.log(res);
});
修改完成后,重新运行一下项目。即可完成跨域请求操作。
请求结果如下: