Javascript 如何阅读正文/响应承诺中的标题
我正在使用Javascript 如何阅读正文/响应承诺中的标题,javascript,fetch,response-headers,fetch-api,Javascript,Fetch,Response Headers,Fetch Api,我正在使用获取API调用API端点。 如何阅读已解决的body promise中的响应正文和标题 下面是我的代码片段: fetch(url, { credentials: 'include', method: 'post', headers: { "Content-Type": "application/json; charset=utf-8", }, body: JSON.stringify({ e
获取API
调用API端点。
如何阅读已解决的body promise中的响应正文和标题
下面是我的代码片段:
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中所述,您可以使用以下代码段获取响应头:
fetch(myRequest).then(function(response) {
var contentType = response.headers.get("content-type");
if (contentType && contentType.indexOf("application/json") !== -1) {
return response.json().then(function(json) {
// process your JSON further
});
} else {
console.log("Oops, we haven't got JSON!");
}
});
对于正文您将找到一些示例。我需要获取处理JSON的标题。在我的示例中,您可以在JSON方法
response.headers.get(“内容类型”)
中访问contentType-这很有帮助,谢谢。