I want to make HTTP Post request to external API, but as I'm trying to do it from React with axios I have a CORS error (No 'Access-Control-Allow-Origin' header is present on the requested resource). At the same time while making this request in .NET everything seems to be ok. I don't have a clue why is it working like this, so maybe someone can figure it out.
React request:
var bodyFormData = new FormData();
bodyFormData.append('key', 'apiKey');
bodyFormData.append('function', 'getTeams');
async function fetchData() {
await axios({
url: 'https://external.api/api/',
method: 'POST',
data: bodyFormData,
withCredentials: true,
headers: {
'Content-Type': 'multipart/form-data',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
},
})
.then((response) => {
console.log(response)
})
.catch((err) => {
console.log(err)
});
}
fetchData();
.NET request:
var request = (HttpWebRequest)WebRequest.Create("https://external.api/api/");
var postData = "key=apiKey";
postData += "&function=getTeams";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();