【问题标题】:Why xhr request is happening in this code?为什么在这段代码中发生 xhr 请求?
【发布时间】:2023-01-13 19:39:44
【问题描述】:

我在浏览器的本地 JS 字典变量 asCache 中缓存了一些数据。然后我首先检查字典中是否存在该键。如果它存在,那么我只返回数据,否则我继续做 axios 请求。代码看起来像这样:

export default class ActivityStatsCard extends React.Component { 

    asCache = {} // cache dictionary 

    async getActiveTimePercentages(fromDate, toDate) {
        var url = '/stats/ahs/';

        let key = 'c-' + this.props.routeProps.match.params.cId 
            + '-from-' + new Date(fromDate).toUTCString()
            + '-to-' + new Date(toDate).toUTCString()

        // if the data is cached, return it (dont do axios request)
        if (this.asCache.hasOwnProperty(key)) 
            return this.asCache[key]

        // if the data is not cached, make axios request
        const axiosInstance = axios.create(); 

        try {
            const response = await axiosInstance.get(url,
                {
                    params: {
                        'format': 'json',
                        'cId': this.props.routeProps.match.params.cId,
                        'FromDate': new Date(fromDate).toUTCString(),
                        'ToDate': new Date(toDate).toUTCString(),
                        'from_getPs': 'True'
                    }
                }
            )

            let data = response.data

            return data;
        } catch (err) {
            console.error(err);
        }
    }
    //...
}

问题是,即使缓存了数据,它也显示它在开发工具的网络选项卡中发出了 xhr 请求。但是我觉得它并没有发出真正的请求,因为请求只需要 12 毫秒:

通常服务器端处理至少需要 55 毫秒,当我开始新会话并且没有数据缓存在 asCache 变量中时,我总是观察到这一点。但是如果它确实没有发出任何 xhr 请求,那么为什么它显示它已经在网络选项卡中完成了一些,如上面的屏幕截图所示?

【问题讨论】:

    标签: javascript reactjs ajax axios xmlhttprequest


    【解决方案1】:

    即使缓存了数据,您在浏览器开发人员工具的网络选项卡中看到请求的原因是因为请求仍在发送到服务器,但处理速度非常快并返回状态代码为的响应304(未修改)。这意味着浏览器具有资源的缓存版本,并且服务器指示缓存版本仍然有效并且可以使用。

    xhr 请求仍在发送到服务器,它只是快速返回,因为服务器认识到它已经在其缓存中拥有最新版本的数据,并发回 304 Not Modified 状态代码来指示这一点。

    浏览器仍然会在开发者工具中显示请求,因为它仍在发送,但实际的数据传输和处理时间要少得多,因为服务器实际上并没有发送任何新数据。

    您可以尝试在服务器端代码中添加一些日志语句来检查是否正在发出实际请求。 此外,您可以检查浏览器的缓存存储以确认数据是否存储在那里。

    简而言之,数据正在缓存中,但浏览器仍在向服务器发送请求,以检查缓存数据是否仍然有效。如果服务器确认缓存数据仍然有效,它会发回 304 Not Modified 状态代码,浏览器使用缓存数据,这就是为什么您在网络选项卡中看到请求但处理时间非常短的原因。

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      • 2012-08-29
      • 2014-11-12
      • 1970-01-01
      • 2015-01-03
      相关资源
      最近更新 更多