封装

97 阅读1分钟

封装接口

首先创建一个idnex.js文件

import axios from 'axios'

/* 创建一个axios实例化对象instance */

var instance = axios.create({

/* 基础路径 / baseURL: '这里是具体路径', / 设置超时时间 */ timeout: 5000 });

instance.interceptors.request.use(

config => {

localStorage.token && (config.headers.Authorization = localStorage.token)

return config

},

error => {

return Promise.error(error)

} )

axios.interceptors.response.use(response => {

return response

}, error => { return error })

/* 参数methods默认值是get,path表示具体路径,post需要给data传参默认值是空对象 get请求需要给params传参默认值是空对象 */

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

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

method,

url:path,

params,/* get方法 */

data/* post方法 */

})

.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 usersGet = (path,params)=>httpServe(path,params)

/* 获取左侧菜单列表 */

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

/* 添加用户 */

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