fetch() 在我的 React 应用程序中发出多个 API 请求

fetch() Making Multiple API Requests in my React App

我正在开发 React 应用程序,为了发出 API 请求,我使用了 fetch(),但由于某些未知原因 fetch() 导致了多个 API 请求而我只期待一个。

在当前情况下,我在浏览器的“网络”选项卡中收到 3 个请求:

同样负责的代码是:

componentDidMount() {
    var planet_id = this.props.match.params.id;
    let planetData = [];
    apiFetch('planets', false, planet_id).then(function(jsonResponse) {
        planetData = jsonResponse;
    }).then(data => this.setState({ 
        planet: planetData,
        loading: false
    }));
}

apiFetch() 的定义:

export function apiFetch(fetchParam, fullUrl = false, id = false) {
let fetchItem;

let apiUrl;

if (fullUrl) {
    apiUrl = fetchParam;
} else {
    switch (fetchParam) {
        case 'people': {
            fetchItem = Constants.apiPeople;
            break;
        }
        case 'planets': {
            fetchItem = Constants.apiPlanets;
            break;
        }
        default: {
            fetchItem = Constants.apiPlanets;
        }
    }
    apiUrl = Constants.apiBaseUrl + fetchItem;
    apiUrl += id ? ('/' + id) : '';
    apiUrl += Constants.apiFormat;
}

return fetch(apiUrl, {
    method: Constants.fetchMethod,
    cache: Constants.apiNoCache
})
.then(response => response.json())
.catch(error => console.error('Error in API:', error));
}

应用程序的流程很好,似乎按预期工作,但我无法弄清楚是什么导致了多个 API 请求。

开发者控制台中可见的前两个请求显示状态代码 301 (Moved Permanently)。您的后端或 Web 服务器似乎配置为重定向您使用模式 2?.

发出的请求

如果您从 fetch 发送正确的 URL(不会导致后端重定向),那么您将开始在控制台中看到一个请求。

终于找到问题了,问题出现是因为 URL.

末尾缺少尾部斜杠 (/)

API 期望在末尾有一个 /。更新代码:

apiUrl = Constants.apiBaseUrl + fetchItem + '/';
apiUrl += id ? (id + '/') : '';
apiUrl += Constants.apiFormat;