如果我获得登录令牌并在标头中发送内容类型,该如何在react-native中获取数据??

问题描述 投票:0回答:2

我是react-native的初学者,我想使用fetch向API发送标头中的登录令牌和内容类型,请帮助我该怎么做?

react-native
2个回答
0
投票

您可以创建一个身份验证标头帮助器功能,并可以在每个请求中使用它。它将在AsyncStorage中检查auth令牌,并将其添加到标头(如果在AsyncStorage中找到)。

export function authHeader() {
    return new Promise((resolve, reject) => {
        var responseObj = {
            'X-Requested-With': 'XMLHttpRequest',
            'credentials': 'include'
        };

        AsyncStorage.getItem("customer").then((res) => {
            let customer = JSON.parse(res);
            if (customer && customer.token) {
                console.log(customer.token)
                responseObj['Authorization'] = 'Bearer ' + customer.token
                resolve(responseObj)
            } else {
                resolve(responseObj)
            }
        }).catch(() => {
            resolve(responseObj)
        });
    })       
}

然后在获取中,只需在标题部分调用此函数。

fetch('API ENDPOINT', {
    method: 'POST',
    body: postData,
    headers: await authHeader()
})
.then(async (responseJson) => responseJson.json())
.then((response) => console.log(response))
.catch((error) => console.log(error)).done();

0
投票

签出https://reactnative.dev/docs/0.60/network

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  }),
});
© www.soinside.com 2019 - 2024. All rights reserved.