开发中,通常会将http相关的代码写到一个文件中,方便项目统一管理。那如何封装http请求呢?
目录
- srccommon/http.js
- common/api.js
- view/test.vue
AXIOS
// http.jsimport axios from \'axios\'const http = {}export const env = process.env.NODE_ENV === \'development\'axios.defaults.baseURL = env ? \'/api\' : \'/\'// 添加请求拦截器axios.interceptors.request.use(function (config) {// 在发送请求之前做些什么return config;}, function (error) {// 对请求错误做些什么return Promise.reject(error);});// 添加响应拦截器axios.interceptors.response.use(response => {// console.log(response)if (response.status === 200) {return response.data} else {return false}}, err=> {// 响应错误})http.axios = axios// 上传文件用请求头http.headersMultipart = {headers: { \'Content-Type\': \'multipart/form-data\' }}// 请求数据转formDatahttp.json2FormData = data => {var params = new FormData()for (let key in data) {params.append(key, data[key])}return params }//TODOexport default http
API
// api.js// 所有接口写在这个文件// 接口命名统一驼峰式命名import http from \'../http\'let axios = http.axiosconst API = {/*** url getTest* method get* params json*/getTest(params){return axios.get(\'/getTest\', {params})}/*** url postTest* method post* params json*/postTest(params){return axios.post(\'/postTest\', params)}/*** url postTest* method post + get* params json*/formdataTest(params){return axios.post(\'/postTest\', params, { params } )}/*** url formdataTest* method post* params formdata*/formdataTest(params){return axios.post(\'/postTest\', http.json2FormData(params))}}export default API
页面调用
// test.vueimport API from \'@/common/api\'// 调用方式1API.postTest(params).then(res => {}).catch(err => {})// 调用方式2 方法外需要加 asynclet res = await API.postTest(params)