Alex Martínez
Alex Martínez

Reputation: 41

Reactjs fetch with credentials doesn't seem to work

I'm trying to do a GET request with a Bearer key and can't figure why it's not working. In Postman, the GET request works perfectly, but in my React.js app can't make it happen. I get a 401 Unauthorized error in console log. I added the mode: 'no-cors' because otherwise I have a Failed to fetch error.

const token = 'https://website.com'
const key = 'XXXXXXXXXXXXX'
const obj = {
  method: 'GET',
  mode: 'no-cors',
  withCredentials: true,
  headers: {
    'Authorization': 'Bearer ' + key,
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json'
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      orders: []
    };
  }

  componentDidMount() {
    fetch(token, obj)
    .then(res => res.json())
    .then(
      (result) => {
        console.log(result)
        this.setState({
          isLoaded: true,
          orders: result.order
        });
      },
      (error) => {
        console.error(error)
        this.setState({
          isLoaded: true,
          error
        });
      }
    )
  }

  render () {
    const { error, isLoaded, orders } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div>
          {orders.order.number}
        </div>
      );
    }
  }
}

This is how the object should look like. Postman GET response

This is the console log errors I get. Console log errors

Without the mode: 'no-cors' I get this problem, how can I solve it? Failed to fetch error

Any ideas on what might be the problem?

Thanks!

Upvotes: 2

Views: 2539

Answers (2)

Alex Mart&#237;nez
Alex Mart&#237;nez

Reputation: 41

I could resolve it by simply taking out mode: 'no-cors' and 'Access-Control-Allow-Origin': '*'. So the object sent in fetch will end up like this:

const obj = {
  method: 'GET',
  withCredentials: true,
  headers: {
    'Authorization': 'Bearer ' + key,
    'Content-Type': 'application/json'
  }
}

Upvotes: 2

wang
wang

Reputation: 612

If you use no-cors mode, the browser will not send headers that are not on the CORS safe list. Therefore, the "authorization" header will not be sent, and the server will not receive it and respond to the 401 code.

Here are more details. Using fetch API with mode: 'no-cors', can’t set request headers

Solution: Remove mode: no-cors, and the server responds to the cors request. Or just keep the content-type header.

Upvotes: 0

Related Questions