我正在使用fetch API
调用API端点。如何读取已解决正文承诺中的响应正文和标头?
我的代码片段如下:
fetch(url, {
credentials: 'include',
method: 'post',
headers: {
"Content-Type": "application/json; charset=utf-8",
},
body: JSON.stringify({
email: email,
password: password,
}),
})
.then(response => response.json())
.then(function(response) {
// How to access response headers here?
});
如 Fetch API 文档中所述,您可以使用以下代码段获取响应标头:
fetch(myRequest)
.then((response) => {
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new TypeError("Oops, we haven't got JSON!");
}
return response.json();
})
.then((data) => {
/* process your data further */
})
.catch((error) => console.error(error));
对于身体,你会在这里找到一些例子。