I am pretty new to CORS. I am building a React App which simply posts data to a backend API. According to the API documentation I have to send a BASIC Authentication Header along with the request which is exactly what I am doing. The request works just fine when I send it through POSTMAN. But when I make the same request from my APP it says Invalid API Key. Below is my code:
App.js:
import React from 'react';
class App extends React.Component{
state = {
data: 'data'
};
handleClick = async () =>{
const res = await fetch('https://myapi.com/post',{
method: 'POST',
body: JSON.stringify({tp:'0'}),
mode: 'cors',
headers: {
content-type:'application/x-www-form-urlencoded',
Authorization : 'Basic ' + new Buffer('username:password').toString(base64)
}
});
const data = await res.json();
this.setState({data});
}
render() {
return(
<div>
<p>{this.state.data}</p>
<button onClick={this.handleClick}>Post</button>
</div>
);
}
}
I looked into the issue and found out that the headers are not being set when sending the request. When further digging into it I found out that the above request is not a simple request and hence the browser makes a preflight OPTIONS request to server. I do not know how the server is handling the requests but I think the server is not configured to handle the preflight OPTIONS. I might be wrong. I do not have any access to the server code. The same request through CORS Anywhere proxy and POSTMAN client is working fine but not while using the actual app. I used create-react-app to setup the boilerplate.
All I get is an Invalid API Token Error while sending request through the app.
Any help on how to get the headers through to the server would be appreciated.