【问题标题】:fetch() Making Multiple API Requests in my React Appfetch() 在我的 React 应用程序中发出多个 API 请求
【发布时间】:2018-10-26 16:29:11
【问题描述】:

我正在开发一个 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 请求。

【问题讨论】:

    标签: javascript reactjs react-router single-page-application fetch-api


    【解决方案1】:

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

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

    【讨论】:

    • 但是我没有发送任何其他 URL 来获取,只是从代码中调用了一个 API 调用。
    • 问题是,无论您形成什么 URL 都会导致来自后端的重定向响应,并且 fetch 遵循重定向
    【解决方案2】:

    终于找到问题了,问题出现是因为网址末尾缺少斜杠(/)。

    API 需要一个 / 结尾。更新代码:

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

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 2020-11-22
      • 1970-01-01
      相关资源
      最近更新 更多