問題描述
在我的 React 應用程序中,我有以下 API POST 以允許用戶編輯他們的個人資料(名稱和圖像).
in my React app, I have the following API POST to allow the user to edit their profile (name and image).
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 中發送...
The problem with the above is the header with the Authorization token is not being sent in the POST...
如何在上面的 fetch 請求中獲取要發送的 Authorization 標頭?
How can I get the Authorization header to be send in the fetch request above?
僅供參考,對于非多部分表單,授權令牌已成功發送,如下所示:
FYI, for non-multipart forms, the authorization token is sent successfully like so:
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;
});
}
推薦答案
如果你設置了任何特殊的請求頭,你不能使用 no-cors
模式,因為使用它的效果之一request 是它告訴瀏覽器不允許您的前端 JavaScript 代碼設置除 CORS 安全列出的請求標頭.請參閱規范要求:
You can’t use no-cors
mode if you set any special request headers, because one of effect of using it for a request is that it tells browsers to not allow your frontend JavaScript code to set any request headers other than CORS-safelisted request-headers. See the spec requirements:
要將 name/value 對附加到 Headers
對象 (headers),請運行以下步驟:
To append a name/value pair to a
Headers
object (headers), run these steps:
- 否則,如果 guard 是
request-no-cors
";并且 name/value 不是 CORS-safelisted request-header,返回.
- Otherwise, if guard is "
request-no-cors
" and name/value is not a CORS-safelisted request-header, return.
在該算法中,return
等同于在不將該標頭添加到 Headers 對象的情況下返回".
In that algorithm, return
equates to "return without adding that header to the Headers object".
Authorization
不是 CORS-safelisted request-header,因此如果您使用 mode: 'no-cors'
請求,您的瀏覽器將不允許您設置.Content-Type: application/json
也一樣.
Authorization
isn’t a CORS-safelisted request-header, so your browser won’t allow you to set if you use mode: 'no-cors'
for a request. Same for Content-Type: application/json
.
如果您嘗試使用 no-cors
模式的原因是為了避免在不使用時出現的其他問題,則解決方案是修復導致其他問題的根本原因.因為無論您試圖解決什么問題,mode: 'no-cors'
最終都不會成為解決方案.它只會產生不同的問題,比如你現在遇到的問題.
If the reason you’re trying to use no-cors
mode is to avoid some other problem that occurs if you don’t use, the solution is to fix the underlying cause of that other problem. Because no matter what problem you might be trying to solve, mode: 'no-cors'
isn’t going to turn out to be a solution in the end. It’s just going to create different problems like what you’re hitting now.
這篇關于當使用 mode: no-cors 請求時,瀏覽器沒有添加我在前端代碼中設置的請求標頭的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!