当前位置: 首页>后端>正文

axios封装

// 封装请求  附带elment
import axios from 'axios'
import { ElMessage } from 'element-plus'
// 请求
const http = axios.create({
    baseURL: "",
    timeout: 100000
})
// 请求拦截
http.interceptors.request.use(config => {
    //请求头设置
    let token = localStorage.getItem('token') || ''
    config.headers.Authorization = token
    return config
}, err => {
    console.log(err);
})
// 响应拦截
http.interceptors.response.use(arr => {
    // 对响应码的处理
    switch (arr.data.meta.status) {
        case 200:
            ElMessage({
                message: arr.data.meta.msg,
                type: 'success',
            })
            break;
        case 201:
            ElMessage({
                message: arr.data.meta.msg,
                type: 'success',
            })
            break;
        case 204:
            ElMessage({
                message: arr.data.meta.msg,
                type: 'success',
            })
            break;
        case 400:
            ElMessage({
                message: arr.data.meta.msg,
                type: 'warning',
            })
            break;
        case 401:
            ElMessage({
                message: arr.data.meta.msg,
                type: 'warning',
            })
            break;
        case 403:
            ElMessage({
                message: arr.data.meta.msg,
                type: 'warning',
            })
            break;
        case 404:
            ElMessage({
                message: arr.data.meta.msg,
                type: 'warning',
            })
            break;
        case 422:
            ElMessage({
                message: arr.data.meta.msg,
                type: 'warning',
            })
            break;
        case 500:
            ElMessage({
                message: arr.data.meta.msg,
                type: 'error',
            })
            break;
    }
    return arr.data.data
}, err => {
    console.log(err);
})
// 
export default http
// 封装请求参数
import http from './http.js'
 
function request({ method = "get", url, data = {}, params = {} }) {
    return http({
        method,
        url,
        data,
        params,
    })
}
 
export default request
// 封装页面请求
import request from '@/network/request.js'
 
// api请求
 
// post方式
export const POST= (data) => request({ url: '/post', method: "post", data, })
 

// get方式
export const GET= (params) => request({ url: '/get', params, })
 


https://www.xamrdz.com/backend/3vt1945713.html

相关文章: