使用Fetch API发送类型:multipart / form-data,如何发送授权标头?

时间:2017-06-25 15:35:24

标签: javascript reactjs cors fetch-api

在我的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;
    });
  }

2 个答案:

答案 0 :(得分:2)

如果您想要设置任何特殊请求标头,则无法使用mode: 'no-cors',因为它对请求使用它的一个效果是它告诉浏览器不允许您的前端JavaScript代码设置任何请求标头其他比CORS-safelisted request-headers。见the spec requirements

  

要将名称/值(名称 / )对附加到Headers对象(标题),请运行这些步骤进行:

     
      
  1. 否则,如果 guard 是" request-no-cors"和名称 / 不是CORS-safelisted request-header,返回。
  2.   

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

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

如果您尝试使用mode: 'no-cors'的原因是为了避免在您不使用时出现的其他问题,解决方案是解决其他问题的根本原因。因为一般而言,无论您可能尝试解决什么问题,mode: 'no-cors'最终都不会成为解决方案。它只是会产生不同的问题,就像你现在正在打的那样。

答案 1 :(得分:0)

通过使用以下代码,您可以使用授权或承载

进行获取请求
    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
    }));