首页 > 解决方案 > GET api 不能在 react native 中工作,但相同的 api 可以与其他工具一起使用

问题描述

我对第三方 API 有一个奇怪的问题。我正在尝试执行GETAPI 的操作,但它会403 error在 react-native 中引发一个操作,但相同的GETAPI 适用于 Postman、Web 浏览器控制台。我无法解决这个问题。

我试图添加credentials: true, user-agent same as a web browser,但没有任何效果。

代码是:

axios.get(`https://api.thirdparty.org/username/file/src`, {
        headers: {
            Authorization: "token"
        } 
    }).then(response => {
        console.log(response.data)
        return {
            status: 200,
            data: response.data
        }
    }).catch(err => {
        console.log(err.response)
        return {
            status: 400,
            message: 'Incorrect details'
        }
    })

这是GETapi 的 Postman 标头在此处输入图像描述

提前致谢

标签: javascriptreactjsreact-nativepromiseaxios

解决方案


使用 try and catch

throw 语句允许您创建自定义错误。

从技术上讲,您可以抛出异常(抛出错误)。

getApiData = async () =>{
    try {
        const url =  "https://api.thirdparty.org/username/file/src";
        const response = await fetch(url);
        if(response.status !== 200){
            throw("bad request");
        }
        const result = await response.json();
        return result;
    } catch(err){
        throw(err)
    }
}


推荐阅读