1

I am trying to create a site where I will consume a web-api and display "users" on the site. I have an API-key that I have to put in the header as "x-api-key".

This is my code at the moment:

import React, { Component } from 'react';
import './App.css';

class App extends Component {

constructor(props) {
  super(props);
  this.state = {
    isLoaded: false,
    items: []
  }
}

componentDidMount() {


  const myHeaders = new Headers();

  myHeaders.append('x-api-key', 'KEY_HERE');
  myHeaders.append('Content-Type', 'application/x-www-form-urlencoded');
  myHeaders.append('cache-control', 'no-cache')

  fetch('URL_HERE', {
    method: 'GET',
    headers: myHeaders,
    async: true,
  })
  .then(res => res.json())
  .then(json => {
    this.setState({
      isLoaded: true,
      items: json,
    })
  });
}

  render() {
  var{isLoaded, items} = this.state;
  if(!isLoaded) {
    return <div>Loading...</div>;
  }

  else{
   return (
     <div className="App">
       <ul>
         {items.map(item => (
           <li key={item.id}>
             Name: {item.name} | Id:{item.id}
           </li>
         ))};
       </ul>
     </div>
   );
  }
}

}

export default App;

The problem is I get these error messages in the console:

Failed to load http://URL/users: Response for preflight does not have HTTP ok status.

Uncaught (in promise) TypeError: Failed to fetch

When I tried making a GET call in Postman I succeeded. So I suppose the problem is that the api-key doesnt get implemented in the header properly.

Appreciate the help, please let me know if there is anything else you need to know!

7
  • It's a CORS issue - make sure the server allows cross origin requests Commented Oct 18, 2018 at 1:53
  • I do not have access to the server. I downloaded the "Allow-Control-Allow-Origin" extension to chrome but no luck. Thank you for your answer Commented Oct 18, 2018 at 1:55
  • Go into your chrome console, and head to the network tab. Execute the request, and then click on the actual request being generated. Make sure in the request headers, you see the X-api-key, and ensure the request is being called properly. Commented Oct 18, 2018 at 1:56
  • "Allow-Control-Allow-Origin" extension clearly a bad extension or one that doesn't understand preflights - use your server to proxy the request to that server that is not yours - this is the simplest and safest solution when a host does not allow CORS Commented Oct 18, 2018 at 1:58
  • Thanks Frankerz, I see this in the request header in chrome>network tab: Access-Control-Request-Headers: cache-control,x-api-key Access-Control-Request-Method: GET. So, I suppose it looks okay? Jaromanda, I will look that up, thanks. Commented Oct 18, 2018 at 2:01

2 Answers 2

1

You need to remove below line from your code and after that, you need to handle OPTIONS method from server-side.

myHeaders.append('cache-control', 'no-cache')

You are getting this error because you are adding a header with 'x-api-key'. you have made the request complex. This requires the browser to make a preflight OPTIONS request to ask for permission to send the complex request.

The server you are making the request to is responding saying that OPTIONS requests are not allowed to that URL

You will need to modify the server and handle OPTION method properly so that it responds appropriately to the preflight CORS request.

You are not getting this error in postman because Postman doesn't need to make a preflight request.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, very informative. Solved the problem server-side. (How do I mark this as answered?)
If this is helpful for you then, please upvote and mark as the correct solution for you from arrow shown in the left side. Thank you
0

Try to use axios if you want to fetch data using api. It can be used at client side and server side as well and very much easy as well. Here is the GitHub repo for your guide. https://github.com/axios/axios

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.