nuxt使用axios的跨域处理配置
npm i axios qs
npm i @nuxtjs/axios @nuxtjs/proxy --save-dev
plugins/axios.js
//使用qs将请求从参数转化位字符串
importqsfrom"qs";
exportdefaultfunction({ $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);
});
}
nuxt.config.js
plugins: [
{src:"~plugins/axios.js",ssr:true},
],
//处理跨域问题
modules: ["@nuxtjs/axios","@nuxtjs/proxy"],
axios: {
retry: {retries:3},
//开发模式下开启debug
debug: process.env._ENV =="production"?false:true,
//设置不同环境的请求地址
baseURL:
process.env._ENV =="production"
?"http://localhost:3000/api"
:"http://localhost:3000/api",
withCredentials:true,
},
proxy: {
//开启代理
"/api/": {
target:"http://192.168.1.2:10086/v1",
pathRewrite: {"^/api/":""}
}
}