人生而自由
却无处不在枷锁之中

Vue 中封装ajax统一处理 ajax 请求错误

封装axios,新建api.js

import axios from 'axios'
import NProgress from 'nprogress'

axios.interceptors.request.use(config => {
    NProgress.start()
    return config
}, error => {
    return Promise.reject(error)
})

axios.interceptors.response.use(response => response, error => Promise.resolve(error.response))

function checkStatus(response) {
    NProgress.done()
    if (response.status === 200 || response.status === 304) {
        return response
    }
    return {
        data: {
            code: -404,
            message: response.statusText,
            data: response.statusText,
        }
    }
}

function checkCode(res) {
    if (res.data.code !== 200) {
        alert(res.data.message)
    }
    return res
}

export default {
    post(url, data) {
        return axios({
            method: 'post',
            url,
            data: JSON.stringify(data),
            timeout: 30000,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Content-Type': 'application/json; charset=UTF-8'
            }
        }).then(checkStatus).then(checkCode)
    },
    get(url, params) {
        return axios({
            method: 'get',
            url,
            params,
            timeout: 30000,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        }).then(checkStatus).then(checkCode)
    }
}

在组件中使用

import api from '../api.js' // 改成对应的路径
export default {
  async mounted() {
    const { data: { code, data }} = await api.post('/comment/post', {title: 'title'})
    if (code === 200) {
        console.log(data)
    }
    const { data: { code, data }} = await api.get('/comment/get', {page: 1})
    if (code === 200) {
        console.log(data)
    }
  }
}
分享到: 更多 (0)

评论 2

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #1

    顶顶顶!!!学习了~

    美股指数1个月前 (08-24)Reply
  2. #2

    301 Moved Permanently
    More info!

    LelandAFtet3周前 (08-30)Reply