1、安装
npm i @nuxtjs/axios @nuxtjs/proxy -D
2、nuxt.config.js配置
exports default { modules: [ '@nuxtjs/axios', ] }
3、nuxt.config.js配置proxy
axios: { proxy: true }, proxy: { '/api': { target: 'http://xxxx:8888', changeOrigin: true, pathRewrite: { '^/api': '/' } } },
4、使用
async asyncData({ $axios }) { const data = await $axios.$get('...') return { data } }
5、使用Nuxt plugin扩展Axios
创建 plugins/axios.js
并定义axios的拦截器
export default function({ $axios, redirect }) { // request interceptor $axios.interceptors.request.use( config => { // do something before request is sent // config.headers['authorization'] = token // 设置token config.headers['Content-Type'] = 'application/json' return config }, error => { // do something with request error return Promise.reject(error) } ) $axios.onRequest(config => { console.log('Making request to ' + config.url) }) // response interceptor $axios.interceptors.response.use( /** * Determine the request status by custom code * Here is just an example * You can also judge the status by HTTP Status Code */ response => { // 响应的数据,可根据接口请看自定义 const code = response.status if (code < 200 || code > 300) { // 可加入异常弹出框 return Promise.reject('error') } else { return response.data } }, error => { console.log('err' + error) // for debug return Promise.reject(error) } ) $axios.onError(error => { const code = parseInt(error.response && error.response.status) if (code === 400) { redirect('/404') } else if (code === 500) { redirect('/500') } }) }
6、添加插件到nuxt.config.js配置文件
plugins: [ '@/plugins/axios' ],
本文作者为gengboxb,转载请注明。