如何使用fetch来制作常用的API调用函数

2024-01-25

我正在尝试创建通用函数来处理来自任何地方的所有 API 调用

我正在使用 React": "^16.8.6" 和 fetch 进行 api 调用

到目前为止我已经弄清楚要做的事情 是

助手.js

export function ApiHelper(url, data = {}, method = 'POST') {
    let bearer = 'Bearer ' + localStorage.getItem('user_token');
    var promise = fetch(url, {
        method: method,
        withCredentials: true,
        // credentials: 'include',
        headers: {
            'Authorization': bearer,
            'X-FP-API-KEY': 'chaptoken', 
            'Content-Type': 'application/json'
        }
    })
    .then(res => res.json())
    .then(
        (result) => {
            console.log(result);
        },
        (error) => {
            error = error;
        }
    )
}

export function AnyOtherHelper() {
    return 'i am from helper function';
}

这是我调用这个函数的地方

componentDidMount() {
    let url = `http://localhost/project/api/getdata`;
    let op = ApiHelper(url);
}

当我控制台结果时then我得到了适当的结果,但我想返回该响应,我该怎么做这部分让我感到困扰 即使我尝试将结果存储在全局变量中,它也不起作用。 另外,只有当承诺得到解决时,我才必须返回响应。


您正在从辅助函数进行异步调用,这意味着您必须从辅助函数返回承诺,如下所示 -

export function ApiHelper(url, data = {}, method = 'POST') {
    let bearer = 'Bearer ' + localStorage.getItem('user_token');
    return fetch(url, {  // Return promise
        method: method,
        withCredentials: true,
        // credentials: 'include',
        headers: {
            'Authorization': bearer,
            'X-FP-API-KEY': 'chaptoken',
            'Content-Type': 'application/json'
        }
    })
        .then(res => res.json())
        .then((result) => {
            console.log(result);
            return result;
        }, (error) => {
            error = error;
        })
}

USAGE

componentDidMount() {
    let url = `http://localhost/project/api/getdata`;
    ApiHelper(url)
    .then(resposnse => {
        console.log(resposnse);
    });
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用fetch来制作常用的API调用函数 的相关文章

随机推荐