1. 注意安装插件 yarn add @nuxtjs/axios yarn add @nuxtjs/proxy
2.在plugins文件夹新建axios.js 内容如下:
import { Message ,Loading} from 'element-ui'
export default function ({ store, redirect, app: { $axios } }) {
let loadingInstance = null;
// 后端接口地址
// $axios.defaults.baseURL = 'https://aabbcc.com/api'
$axios.defaults.baseURL = process.env.NODE_ENV == "development" ? "/api" : "https://aabbcc.com/api"
// Request拦截器:设置Token
$axios.onRequest((config) => {
// 使用Vuex存储Token,并做持久化处理
// console.log(localStorage.getItem("token"))
let noLoda = config.noLoad;
if (!noLoda) {
loadingInstance = Loading.service({
fullscreen: true,
background: "#fff",
});
}
config.headers['Authorization'] = "Bearer" + localStorage.getItem("token")
})
// Error拦截器:出现错误的时候被调用,根据状态码做对应判断并显示全局Message
$axios.onError((error) => {
if (loadingInstance) {
loadingInstance.close();
loadingInstance = null;
}
const code = parseInt(error.response && error.response.status)
switch (code) {
case 400:
Message.error('请求错误')
break;
// 未登录
case 401:
Message.error("Token过期")
break;
case 403:
Message.error('拒绝访问')
break;
case 404:
Message.error(`请求地址出错: ${error.response.config.url}`)
break;
case 408:
Message.error('请求超时')
break;
case 500:
Message.error('服务器内部错误')
break;
case 501:
Message.error('服务未实现')
break;
case 502:
Message.error('网关错误')
break;
case 503:
Message.error('服务不可用')
break;
case 504:
Message.error('网关超时')
break;
case 505:
Message.error('HTTP版本不受支持')
break;
default:
break;
}
// 异常信息
// Message.error(error.response.data.message)
})
// Response拦截器:对正常返回的数据进行处理
$axios.onResponse((response) => {
if (loadingInstance) {
loadingInstance.close();
loadingInstance = null;
}
return response.data
})
}
3.找到nuxt.config.js配置文件添加以下内容:
plugins: [
{ src: '~/plugins/axios.js' ,ssr: false },
],
axios: {
proxy: true,
prefix: '/api', // baseURL
credentials: true,
},
proxy: {
'/api': {
target: 'https://aabbcc.com/api', // 代理地址
changeOrigin: true,
pathRewrite: {
'^/api': '', //将 /api 替换掉
}
}
},
modules: [
'@nuxtjs/axios',
"@nuxtjs/proxy"
],
4.请求使用方法:
this.$axios.post('/duanxin', {
phone: this.iphoneLoginForm.iphone,
}).then((res) => {
this.$message.success(res.message);
})