Ali Hussain
Ali Hussain

Reputation: 896

I am not able to read authorization headers on server side with reactjs fetch and nodejs as REST apis project

I am not able to get headers on server side with reactjs fetch as way of calling api on front end. in old project it was working fine what could be reason of that as my back-end code is not changed

      this.setState({ isProcessing: true });  
      fetch(env.apis.getUsersList, reqOptions)
      .then(res => res.json())
      .then((data) => {
        this.setState({ users: data });  
      })
      .catch((error) => {
           debugger
      });
   }

and this is how i passing header

var reqOptions = {
        method: actionType,
        headers: new Headers({ 
            'Content-Type': 'application/json',
            'authorization': 'Bearer ' + localStorage.token
       }), 
    };
    // debugger
    // if (localStorage.token) {
        // reqOptions.headers.authorization = 'Bearer ' + localStorage.token;   
    // }
    if (data) {
        reqOptions.body = JSON.stringify(data);
    }
    return reqOptions;
    

getting this error message error = TypeError: Failed to fetch

in browser it is basically showing provisional headers are being shown

that is error

enter image description here

Upvotes: 1

Views: 323

Answers (1)

Ali Hussain
Ali Hussain

Reputation: 896

the issue was on server side with the CORS settings for nodejs and fixed doing like that

var cors = require('cors'); 
app.use(cors({credentials: true}));

Upvotes: 1

Related Questions