无论是Vue、React开发中,我们都会用到fetch方法来请求接口api,并且有时请求的方法(post、get)不一样,还需要使用不同的方式请求,所以我们可以直接封装一份自定义Ajax请求。

    1. import * as qs from "qs";
    2. const postHeader = {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'};
    3. const getHeader = {'Content-Type': 'application/json;charset=utf-8'};
    4. export function ajaxFetch(url, data, method) {
    5. if (method === 'get') {
    6. return getFetch(url, data, getHeader);
    7. } else {
    8. return postFetch(url, data, postHeader)
    9. }
    10. }
    11. //post请求
    12. function postFetch(url, data, header) {
    13. return fetch(url, {
    14. method: 'post',
    15. headers: header,
    16. body: qs.stringify(data),
    17. }).then(res => {
    18. return res.json()
    19. })
    20. }
    21. //get请求(请求的参数直接拼接在url上面)
    22. function getFetch(url, data, header) {
    23. let data_url = ''; //拼接的url
    24. let keys = Object.keys(data); //获取传参的键
    25. //拼接传参
    26. for (let i = 0; i < keys.length; i++) {
    27. data_url += `${keys[i]} = ${data[keys[i]]}&`
    28. }
    29. return fetch(`${url}?${data_url}`, {
    30. method: 'get',
    31. headers: header,
    32. }).then(res => {
    33. return res.json()
    34. })
    35. }

    然后我们在url接口文件中直接使用即可

    1. import {ajaxFetch} from "./ajax";
    2. export function getAllUrls(data) {
    3. return ajaxFetch('/api/xxxx', data, 'get');
    4. }