无论是Vue、React开发中,我们都会用到fetch方法来请求接口api,并且有时请求的方法(post、get)不一样,还需要使用不同的方式请求,所以我们可以直接封装一份自定义Ajax请求。
import * as qs from "qs";
const postHeader = {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'};
const getHeader = {'Content-Type': 'application/json;charset=utf-8'};
export function ajaxFetch(url, data, method) {
if (method === 'get') {
return getFetch(url, data, getHeader);
} else {
return postFetch(url, data, postHeader)
}
}
//post请求
function postFetch(url, data, header) {
return fetch(url, {
method: 'post',
headers: header,
body: qs.stringify(data),
}).then(res => {
return res.json()
})
}
//get请求(请求的参数直接拼接在url上面)
function getFetch(url, data, header) {
let data_url = ''; //拼接的url
let keys = Object.keys(data); //获取传参的键
//拼接传参
for (let i = 0; i < keys.length; i++) {
data_url += `${keys[i]} = ${data[keys[i]]}&`
}
return fetch(`${url}?${data_url}`, {
method: 'get',
headers: header,
}).then(res => {
return res.json()
})
}
然后我们在url接口文件中直接使用即可
import {ajaxFetch} from "./ajax";
export function getAllUrls(data) {
return ajaxFetch('/api/xxxx', data, 'get');
}