1.封裝http.js
import axios from 'axios'
const successCode = 0
const instance = axios.create({
baseURL: '/api',
withCredentials: true, // 跨域類型時(shí)是否在請(qǐng)求中協(xié)帶cookie
})
export default class HttpUtil {
static get(url, params = {}) {
return new Promise((resolve, reject) => {
instance.get(url, { params }).then(({ data }) => {
//根據(jù)后臺(tái)配置回調(diào)參數(shù)進(jìn)行封裝
}).catch((err) => {
//異常處理
reject({ err: JSON.stringify(err) })
})
})
}
static post(url, params = {}) {
return new Promise((resolve, reject) => {
instance.post(url, { data: params }).then(({ data }) => {
}).catch((err) => {
reject({ err: JSON.stringify(err) })
})
})
}
}
2.項(xiàng)目的api統(tǒng)一封裝
import $http from './http'
export const getData = (params) => {
return $http.get('/api', params)
}
3.在項(xiàng)目中使用
import {getData} from '../http/index'
async getList(){
return await getData({
index:1,
like:7
})
}