axios封装

101 阅读1分钟

// index.js 

import axios from 'axios' var instance = axios.create({

 baseURL: '*******', 

 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.request.use( 

 response => { 

 return response 

 }, error => { 

 return Promise.error(error) 

 }) 

 export const httpServe = (path, params = {}, method = 'get', data = {}) => {

return new Promise((resolve, reject) => {

 instance({ 

 url: path, 

 params, 

 method, 

 data 

 }) .

then(res => { resolve(res) }) 

 .catch(err => { reject(err) }) }) } 

 // request.js

 import {httpServe} from '@/http/index.js' 

 // 登录请求 

export const loginPost = (path,data)=> httpServe(path,{},'post',data) 

// 左侧菜单列表 

export const menusGet = (path,params)=> httpServe(path,params) 

// 用户列表 

export const usersGet = (path,params)=> httpServe(path,params)

 // 添加用户 

export const addusersPost = (path,data)=> httpServe(path,{},'post',data)