You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Fetch API的Promise链中传递HTTP响应状态码?

解决方案

你只需要在第一个then回调中,将response.status和response.json()的结果打包成一个对象返回即可,具体修改如下:

fetch('api/register', {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(jsonObj)
})
    .then(response => {
        const responseClone = response.clone();
        const status = response.status; // 先保存状态码
        if (!response.ok) {
            console.log(`HTTP ERROR STATUS CODE: ${status}`);
        }
        // 将JSON解析结果和状态码打包成对象返回
        return response.json().then(data => ({ data, status }));
    })
    .then(function (result) {
        // 解构拿到data和status,传给目标函数
        processDataFromServer(result.data, result.status);
    }, function (rejectionReason) {
        console.log('JSON Parsing Error:', rejectionReason, responseClone);
        responseClone.text()
            .then(function (bodyText) {
                console.log('Cannot parse as JSON:', bodyText);
            });
    })
    .catch(error => {
        console.log("Error: " + error)
        deplayError(error);
    });

如果习惯ES6解构语法,还可以简化第二个then的处理:

.then(({ data, status }) => {
    processDataFromServer(data, status);
})

核心逻辑是利用response.json()本身是Promise的特性,在它的then回调中把解析后的data和预先保存的status组合成对象返回,这样后续的then就能同时拿到这两个值。

内容的提问来源于stack exchange,提问作者PC.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 13:54:52