vue-cli3中解决axios跨域问题(以360壁纸为例)
一、先在vue项目文件夹里的根目录中新建 vue.config.js文件(与package.json同一级)
二、在 vue.config.js文件中写入以下代码
module.exports = {
devServer: {
proxy: 'http://cdn.apc.360.cn' //这里写入你要获取数据的服务器的地址
}
}
修改完后重新打开命令运行服务
这里不做详细介绍想了解的可以自行搜索proxy中有许多配置项
三、在vue文件中调用接口
getPhotoNav(){
this.$http.get("/index.php?c=WallPaper&a=getAllCategoriesV2&from=360chrome").then(res =>{
console.log(res)
})
四、如果发现获取到的data为空的话,将传递的json数据转为form data,修改main.js文件
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
if(config.method!='get'){
config.data=qs.stringify(config.data);
}
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
return config;
},function (error) {
return Promise.reject(error)
})