获取 API 响应代码与网络选项卡响应代码不同

Fetch API Response Code Differs from Network Tab Response Code

我正在创建一个 React 组件,该组件旨在根据页面是否被缓存来检查隐私政策页面的更新。我有两个问题 -

  1. 响应对象显示的响应代码与网络选项卡中显示的响应代码不同。
  2. 不太重要的是,请求被发送了两次,我不确定为什么。这可能是我的逻辑问题或由应用程序中的其他内容引起的。

代码

    //Set the state to undefined initial, it'll
    const [ppChanged, setPPStatus] = useState(undefined);
    function checkPrivacyPolicyChanged(url) {
        try {
            fetch(url)
            .then(
            response => {
                console.log("Response: ", response)
                if (response.ok && response.status !== 304) {
                    //If the response code is 200-299 (ok status), and isn't cached (as indicated by status 304)
                    //Tell the component that the privacy policy has had changes since the user last saw it
                    setPPStatus(true);
                } else if (response.status == 304) {
                    setPPStatus(false);
                } else {
                    console.log(response);
                }
            },
            //Error handling
            error => {throw Error(error)}
            )
        }
        catch(err) {
            console.log(err)
        }
    }
    //If we haven't determined the privacy policy state yet, check for it. (Using manifest.json for testing purposes)
    if (ppChanged == undefined) {

        checkPrivacyPolicyChanged("/manifest.json");
    }

    let color = "green";
    //If a change to the privacy policy is detected, give a visual cue
    if (ppChanged) {color = "purple"};
    return(
        <div style={{color}}>
            {props.children}
        </div>
    );
}

控制台(注意右边的响应代码)

304 返回 - 200 作为提取结果

提取标准描述了这种行为here

  1. If response is null, then:

有关 null body status 的说明请参阅 statusses,这些状态是 101204205304.

10.4 If the revalidatingFlag is set and forwardResponse’s status is 304, then:

10.4.1 Update storedResponse’s header list using forwardResponse’s header list, as per the "Freshening Stored Responses upon Validation" chapter of HTTP Caching. [HTTP-CACHING]

This updates the stored response in cache as well.

10.4.2 Set response to storedResponse.

这意味着 200 状态代码来自您的浏览器之前存储的响应,并且由于收到 304 而正在提供服务。这是有道理的,因为浏览器将无法给你一个响应,除非它再次查询资源(这是试图用这种 304 - Not modified 状态避免的)。

备选方案

您可以改为跟踪请求的以下 headers 之一,并将它们与以前存储的值进行比较:

请求发送了两次

如评论中所述,解决方案是使用 useEffect-hook

useEffect(() => {
  ...
}, []); // Note the empty dependency array ensures that this code will only be executed once during the lifetime of this component.

之所以需要这个是因为在渲染过程中,这个函数会被执行不止一次(例如,在调用setPPStatus之后更新状态)。

当此函数为re-executed时,如果尚未发生更新,if (ppChanged == undefined)块将被执行多次并因此触发多次API调用。

通过使用带有空依赖数组的 useEffect-hook,您可以确保此代码只执行一次。