首页 > 解决方案 > React Native fetch 返回 404 但邮递员执行 200 ok

问题描述

我正在将 Spotify web api 集成到反应原生应用程序中。我对 React Native fetch 有问题。当我在 Postman 中调用 api 时,我得到 200 响应代码,但如果我在模拟器(react native)中运行它,我得到 404 错误代码。我还在 chrome 控制台中编写了 fetch 请求,它运行良好,但在 react native 中它不起作用。

我正在运行的代码:

let response = await fetch(`https://api.spotify.com/v1/browse/featured-playlists?locale=en_US&country=US`, {
        method: 'GET',
        headers: {
            'Accept': 'application/json;charset=utf-8',
            'Content-Type': 'application/json;charset=utf-8',
           'Authorization': 'Bearer BQDT3_xtYLyIsGaqhoTM42Z-k3ijs-hFbzIG89basd7Me-kL4SUWSLgQrxWN3b13DiqU6THfr4VH4Z7klnc' 
        }
    });
    console.log("response",response.status)

标签: react-nativegetfetchhttp-status-code-404spotify

解决方案


我在 React Native v. 0.58.6 中尝试了以下代码

async componentDidMount() {
    let spotifyApiUrl = "https://api.spotify.com/v1/browse/featured-playlists?locale=en_US&country=US";
    let fetchSettings =  {
        method: 'GET',
        headers: {
            'Accept': 'application/json;charset=utf-8',
            'Content-Type': 'application/json;charset=utf-8',
            'Authorization': 'Bearer BQDT3_xtYLyIsGaqhoTM42Z-k3ijs-hFbzIG89basd7Me-kL4SUWSLgQrxWN3b13DiqU6THfr4VH4Z7klnc' 
        }
    };

    fetch(spotifyApiUrl, fetchSettings)
        .then( (response) => response.json() )
        .then( (responseJson) => {
            console.log(JSON.stringify(responseJson));
        })
        .catch((error) => {
            console.log(error);
        });
}

使用以下控制台输出:

{"error":{"status":401,"message":"The access token expired"}}

您是否尝试过插入实际设备以查看是否是模拟器问题?如果您使用真实设备,请记住在运行“react-native run-android”之前在 adb 上转发 tcp 端口

adb reverse tcp:8081 tcp:8081
react-native run-android

推荐阅读