小编Lul*_*Ash的帖子

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

我正在尝试制作通用功能,该功能将处理来自任何地方的所有 API 调用

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

到目前为止,我想出的是

Helper.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'; …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs fetch-api

2
推荐指数
1
解决办法
1462
查看次数

标签 统计

fetch-api ×1

reactjs ×1

typescript ×1