如何使用fetch进行通用的API调用功能 [英] How to make common API call function using fetch

查看:111
本文介绍了如何使用fetch进行通用的API调用功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建通用功能,该功能可以处理来自任何地方的所有API调用

I am trying to make common function which will handle all of my API calls from anywhere

我正在使用react:" ^ 16.8.6并提取用于进行api调用

I am using react": "^16.8.6" and fetch for making api call

到目前为止,我已经确定要做什么 是

So far what i have figure out to do is

Helper.js

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';
}

这是我从中调用此函数的地方

And here is from where i am calling this function

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

当我在then中获得控制台结果时,我得到了适当的结果,但是我想返回该响应,我该如何做这部分却困扰着我 即使我尝试将结果存储在全局变量中,也无法正常工作. 另外,我只能在答应得到解决时才返回响应.

when I console result in then i am getting appropriate result but what i want to return that response how can i do this part is troubling me Even i have try to store the result in global variable and it is not working. Also i have to return the response only when promise is resolved.

推荐答案

您正在通过助手函数进行异步调用,这意味着,您将必须像这样从助手函数返回诺言-

You are making an async call from your helper function which means, you will have to return promise from your helper function like this -

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;
        })
}

用法

componentDidMount() {
    let url = `http://localhost/project/api/getdata`;
    ApiHelper(url)
    .then(resposnse => {
        console.log(resposnse);
    });
}

这篇关于如何使用fetch进行通用的API调用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆