gpt4 book ai didi

javascript - 使用模式 : no-cors for a request, 时,浏览器未添加我在前端代码中设置的请求 header

转载 作者:行者123 更新时间:2023-11-30 11:35:15 28 4
gpt4 key购买 nike

在我的 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 中发送带有授权 token 的 header ...

如何获取要在上面的获取请求中发送的授权 header ?

仅供引用,对于非多部分表单,授权 token 已成功发送,如下所示:

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

最佳答案

如果您设置了任何特殊的请求 header ,则不能使用 no-cors 模式,因为使用它的一个效果是:它告诉浏览器不允许您的前端 JavaScript 代码设置任何请求 header 除了CORS-safelisted request-headers .参见 the spec requirements :

To append a name/value pair to a Headers object (headers), run these steps:

  1. Otherwise, if guard is "request-no-cors" and name/value is not a CORS-safelisted request-header, return.

在该算法中,return 等同于“返回而不将该 header 添加到 Headers 对象”。

Authorization 不是 CORS-safelisted request-header ,因此如果您对请求使用 no-cors 模式,您的浏览器将不允许您设置。 Content-Type: application/json 也是如此。

如果您尝试使用 no-cors 模式的原因是为了避免在您不使用时出现的其他问题,则解决方案是修复该其他问题的根本原因.因为无论您尝试解决什么问题,no-cors 模式最终都不会成为解决方案。它只会产生不同的问题,例如您所击中的内容。

关于javascript - 使用模式 : no-cors for a request, 时,浏览器未添加我在前端代码中设置的请求 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44747874/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com