[英]Request header not set as expected when using 'no-cors' mode with fetch API
[英]When using mode: no-cors for a request, browser isn’t adding request header I’ve set in my frontend code
在我的React應用程序中,我具有以下API POST,以允許用戶編輯其個人資料(名稱和圖像)。
static updateProfile(formData, user_id) {
const request = new Request(`http://localhost:4300/api/v1/profiles/${user_id}`, {
headers: new Headers({
'Authorization': getBearerToken()
}),
mode: 'no-cors',
method: "POST",
body: formData
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
上面的問題是在POST中沒有發送帶有Authorization令牌的標頭...
如何在上面的獲取請求中發送要發送的授權標頭?
僅供參考,對於非多部分形式,授權令牌成功發送,如下所示:
static loadProfile(user_id) {
const request = new Request(`http://localhost:4300/api/v1/profiles/${user_id}`, {
headers: new Headers({
'Authorization': getBearerToken(),
'Accept' : 'application/json',
'Content-Type' : 'application/json',
})
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
如果要設置任何特殊的請求標頭,則不能使用mode: 'no-cors'
,因為對請求使用標頭的影響之一是它告訴瀏覽器不允許前端JavaScript代碼設置除請求標頭以外的任何請求標頭CORS安全列出的請求標頭 。 請參閱規格要求 :
要將名稱/值( 名稱 / 值 )對附加到
Headers
對象( headers ),請運行以下步驟:
- 否則,如果guard是“
request-no-cors
”並且名稱 / 值不是CORS安全列出的request-header ,則返回。
在該算法中, return
等同於“在不將標題添加到Headers對象的情況下返回”。
Authorization
不是CORS安全列出的請求標頭 ,因此如果您使用以下mode: 'no-cors'
,則您的瀏覽器將不允許您設置mode: 'no-cors'
用於請求。 與Content-Type: application/json
相同Content-Type: application/json
。
如果您嘗試使用mode: 'no-cors'
的原因mode: 'no-cors'
是為了避免在mode: 'no-cors'
使用mode: 'no-cors'
時發生其他問題,那么解決方案是解決該其他問題的根本原因。 因為總的來說,無論您想解決什么問題, mode: 'no-cors'
都不會成為解決方案。 這只會造成各種問題,例如您現在遇到的問題。
通過使用以下代碼,您可以使用授權或承載來進行提取請求
var url = "https://yourUrl";
var bearer = 'Bearer '+ bearer_token;
fetch(url, {
method: 'GET',
withCredentials: true,
credentials: 'include',
headers: {
'Authorization': bearer,
'X-FP-API-KEY': 'iphone',
'Content-Type': 'application/json'}
}).then((responseJson) => {
var items = JSON.parse(responseJson._bodyInit);
})
.catch(error => this.setState({
isLoading: false,
message: 'Something bad happened ' + error
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.