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!
"Allow-Control-Allow-Origin" extensionclearly 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