一、最近做的一个后台管理项目,基于antd-pro做的,需要封装基于axios请求,便于开发,直接上代码。
import axios from 'axios'; export const MethodType = { GET: 'GET', POST: 'POST', PUT: 'PUT', DELETE: 'DELETE', PATCH:'PATCH' }; /** * 模块说明:有api_token的请求 */ export const request = (api, method = MethodType.GET, params = {}, config = {}) => { const apiToken = '************'; const data = (method === 'GET') ? 'params' : 'data'; let headers = { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiToken}`, }; if (config.headers) { headers = { ...headers, ...config.headers } } return new Promise((resolve, reject) => { axios({ url: api, method, [data]: params, headers, }).then(resolve) .catch(error => { console.dir(error); Message.error(typeof error.response.data === 'string' ? error.response.data : JSON.stringify(error.response.data)); reject(error); }); }); };
二、另外项目统一管理api请求,将api请求都放在了api.js目录下
示例:
import {MethodType} from "./promise"; const promise = require('./promise'); export const _goodsList = async (page,keyword,catId,onSale)=>{ return await promise.request('/api/admin/goods/list', MethodType.GET, { page, keyword, catId, onSale, }) };
三、使用api方法
import { _goodsList, } from '../utils/api'; @action.bound async handleSearchData(page,keyword,catId,onSale){ await _goodsList(page,keyword,catId,onSale); }
总结:上面的就是项目中api的用法,可以完全按照这样来写