When using mode: no-cors for a request, browser isn’t adding request header I’ve set in my frontend code

前端 未结 2 1842
眼角桃花
眼角桃花 2020-12-21 21:55

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) {
    cons         


        
相关标签:
2条回答
  • 2020-12-21 22:18

    By using below code you can make a fetch request with Authorization or bearer

        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
        }));
    
    0 讨论(0)
  • 2020-12-21 22:33

    You can’t use mode: 'no-cors' if you want set any special request headers, because one of the effects 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:

    To append a name/value (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.

    In that algorithm, return equates to “return without adding that header to the Headers object”.

    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.

    If the reason you’re trying to use mode: 'no-cors' 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 in general 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.

    0 讨论(0)
提交回复
热议问题