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!
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.