![818b3d73f7ceebdeae681e43e5ca69c9.png](https://i-blog.csdnimg.cn/blog_migrate/7d656129c1ef3acfde26173df1ba7ef9.png)
在调试后端接口遇到这样的跨域报错提示:
![9ae7058ba6e27a6a8b62fa58aaf95e88.png](https://i-blog.csdnimg.cn/blog_migrate/e3c6d3b41d43f4d4845fe33bade62f0e.png)
Access to XMLHttpRequest at 'http://192.168.xxx.xxx:xxx/xxxx' from origin 'http://localhost:8010' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:8010, *', but only one is allowed.
调用:
axios.get("http://xxx", {
params: {
}
})
.then(response => {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
但发现将url通过浏览器打开,能直接接收到到后端返回的response,经过配置代理后能成功访问了,配置如下:
1.先用cnpm安装 axios,@nuxtjs/axios,@nuxtjs/proxy 和 qs
cnpm install axios @nuxtjs/axios --save-dev
cnpm install @nuxtjs/proxy qs --save-dev
2.在plugins文件夹下新建axios.js文件:
//使用qs将请求从参数转化位字符串
import qs from"qs";
export default function({ $axios, redirect }){
$axios.onRequest(config=>{
config.data = qs.stringify(config.data, {
allowDots:true
});
returnconfig;
});
$axios.onResponse(response=>{
returnPromise.resolve(response.data);
});
$axios.onError(error=>{
returnPromise.reject(error);
});
}
3.配置nuxt.config.js
var webpack = require('webpack');
module.exports = {
modules: [
['@nuxtjs/axios',"@nuxtjs/proxy"]
],
plugins:[
{src:"~/plugins/axios.js",ssr:true},
],
axios: {
proxy: true,
prefix: '/api', // baseURL
credentials: true,
},
proxy: {
'/api': {
target: 'http://192.168.xxx:xxx/xxx', // 代理地址
changeOrigin: true,
pathRewrite: {
'^/api': '', //将 /api 替换掉
}
}
}
}
4.请求后端接口:
axios.get("/api/xxx", {
params: {
}
})
.then(response => {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
能得到后端返回的response了:
![0c44a5a4feeb47d374c03283c6373541.png](https://i-blog.csdnimg.cn/blog_migrate/f69d52a22eb58fcb933c9bcbb1f13abf.png)
温馨提示:
发布后,发现nuxt太调皮了,这种方式打包静态生成的线上代理的接口报404,代理接口只能在开发环境用
更多参考:[vue中使用axios 代理请求 ,打包之后失效 请求报404]
线上打包跨域其他解决方案:
vue利用axios处理开发环境和生成环境的跨域问题