nuxt中设置请求拦截器

1.创建plugins文件夹,在该文件下创建一个request.js文件

// import request from '@/utils/request'
import axios from 'axios'

export const request= axios.create({
    baseURL: 'https://conduit.productionready.io'
})

export default ({ store }) => {
    // 请求拦截器
    request.interceptors.request.use(function (config) {
        // Do something before request is sent
        const {user} = store.state
        if(user){
            config.headers.Authorization = `Token ${user.token}`
        }
        return config;
    }, function (error) {
        // Do something with request error
        return Promise.reject(error);
    });
    // 响应拦截器
    request.interceptors.response.use(function (response) {
        // Any status code that lie within the range of 2xx cause this function to trigger
        // Do something with response data
        return response;
    }, function (error) {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error
        return Promise.reject(error);
    });
}

2.使用创建api/user.js

import {request} from '@/plugins/request'
export const register = data => {
    return request({
        method: 'POST',
        url: '/api/users',
        data
    })
}

export const login = data => {
    return request({
        method: 'POST',
        url: '/api/users/login',
        data
    })
}

2.在根目录在创建nuxt.config.js

export default{
    plugins: [
        '~/plugins/request.js'
    ]
}

 

你可能感兴趣的:(nuxt,vue)