2016-01-01 50 views
87

我正在嘗試新的提取API,但遇到Cookies問題。具體來說,成功登錄後,將來的請求中會包含Cookie標頭,但Fetch似乎忽略該標頭,並且使用Fetch創建的所有請求都是未經授權的。用Cookie提取API

是否因爲Fetch尚未準備好或Fetch無法與Cookie配合使用?

我用Webpack構建我的應用程序。我也在React Native中使用Fetch,它沒有相同的問題。

回答

139

默認情況下,Fetch不使用cookie。要啓用cookie的,這樣做:

fetch(url, { 
    credentials: "same-origin" 
}).then(...).catch(...); 
+15

同源不再工作,include(請參閱@ Jerry的答案):https://developers.google.com/web/updates/2015/03/introduction-to-fetch – jpic

+0

如何訪問cookie –

+2

@jpic:'include'僅適用於跨源請求,但不適用於同源請求。官方文檔:https://github.com/github/fetch#sending-cookies – HoldOffHunger

79

除了@ Khanetor的回答,對於那些誰與跨域請求工作:credentials: 'include'

樣品JSON讀取請求:

fetch(url, { 
    method: 'GET', 
    credentials: 'include' 
}) 
    .then((response) => response.json()) 
    .then((json) => { 
    console.log('Gotcha'); 
    }).catch((err) => { 
    console.log(err); 
}); 

https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials

+3

雖然你如何設置cookie? – pomo

+0

Cookie是從服務器端設置的。在我的情況下,我使用httponly cookie。 – Khanetor

+2

@Khanetor可以使用javascript的document.cookie設置cookie,然後發送請求? – ospider