2016-05-22 40 views
3

我使用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? 
    }); 

回答

-1

至于说取documentation

你可以得到响应头在这个片段:

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!"); 
    } 
}); 

对于,你会发现here一些例子。

+2

我需要在我处理JSON的地方获取标题。 – LukasMac

+0

在我的示例中,您可以在json方法中访问contentType – Ygalbel