Vue项目中有封装axios

73 阅读1分钟

src > http > index.js

import axios from "axios";

var instance = axios.create({
    baseURL: 'https://......',
    timeout: 3000
})

// 请求拦截器
instance.interceptors.request.use(
    config => {
        // 每次发送请求之前判断是否存在token
        // 如果存在,则统一在http请求的header都加上token,后台根据token判断你的登录情况
        //此处token一般是用户完成登录后储存到localstorage里的
        localStorage.token && (config.headers.Authorization = localStorage.token)
        return config
    },
    error => {
        return Promise.error(error)
    })

// 响应拦截器
instance.interceptors.response.use(response => {
    return response
}, error => {
    return error
})

export const httpServe = (path, params = {}, method = 'get', data = {}) => {
    return new Promise((resolve, reject) => {
        instance({
            method,
            url: path,
            data,
            params
        })
            .then(res => {
                resolve(res)
            })
            .catch(err => {
                reject(err)
            })
    })
}

src > http > request.js

import { httpServe } from "@/http/index.js";
// 登录
export const loginPost = (path, data) => httpServe(path, {}, 'post', data)
// 用户列表
export const usersGet = (path, params) => httpServe(path, params)
// 菜单列表
export const menusGet = (path) => httpServe(path)
// 添加用户
export const adduserPost = (path, data) => httpServe(path, {}, 'post', data)

⭐使用对象解构的方式传参,不用考虑传参顺序,通过key名找到对应的值
修改如下:
src > http > index.js

export const httpServe = ({path, params = {}, method = 'get', data = {}}={}) => {
    return new Promise((resolve, reject) => {
        instance({
            method,
            url: path,
            data,
            params
        })
            .then(res => {
                resolve(res)
            })
            .catch(err => {
                reject(err)
            })
    })
}

src > http > request.js

import { httpServe } from "@/http/index.js";
// 登录
export const loginPost = (path, data) => httpServe({path, method: 'post', data})
// 用户列表
export const usersGet = (path, params) => httpServe({path, params})
// 菜单列表
export const menusGet = (path) => httpServe({path})
// 添加用户
export const adduserPost = (path, data) => httpServe({path, method:'post', data})
// 删除用户
export const userDelete = (path) => httpServe({path, method:'delete'})