当使用 mode: no-cors 请求时,浏览器没有添加请求 header 我已经在我的前端代码中设置了

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

上面的问题是 header 没有在 POST 中发送带有授权令牌的 header...

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

仅供参考,对于 non-multipart 表单,授权令牌已成功发送,如下所示:

  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 设置除 CORS-safelisted request-headers. See the spec requirements 以外的任何请求 header 的代码:

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 等同于“return 而不是将 header 添加到 Headers object”。

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

相同

如果您尝试使用 no-cors 模式的原因是为了避免在不使用时出现其他问题,则解决方案是解决该其他问题的根本原因。因为无论您尝试解决什么问题,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
    }));