JavaScript 获取响应返回未定义

Men*_*des 4 javascript fetch

I\xc2\xb4m 尝试使用 fetch 加载一些服务器数据。这是代码:

\n\n
fetch('/user', {\n    method: 'POST',\n    headers: {\n        Accept: 'application/json',\n        'Content-type': 'application/json'\n    },\n    body: JSON.stringify({\n        data: 'test'\n    })\n})\n.then(response => {\n        if (response.status !== 200) {\n            console.log('Fetch status not OK');\n        }\n        else {\n            console.log('Fetch ok');\n            console.log(response); // Undefined here\n        }\n    })\n.catch(error => {\n        console.log('network error');\n    });\n
Run Code Online (Sandbox Code Playgroud)\n\n

在浏览器(网络)上,我可以看到从服务器返回的响应有效负载,但我的响应包含undefined. 我可以想象这应该很简单,但我无法\xc2\xb4t找出这里发生了什么。

\n

Xav*_*hay 5

我也遇到了类似的问题,不知道response.body返回哪里undefined。与OP的代码并不严格相同,但我猜这可能是同一个问题,而且搜索也把我带到了这里,所以发布我的答案。

发生这种情况是因为尚未读取正文,仅响应标头已到达。访问响应正文的正确方法是:

fetch('/user').then((resp) => resp.json().then((body) => console.log(body)))
Run Code Online (Sandbox Code Playgroud)

此处记录了读取正文的各种方式(如文本、JSON 等)。