I have a React app that sends a JSON object to my API through a POST method. I can get a proper response using Post-man, but from my app, there are CORS issues. I want to be able to send the object to my API, and have the API send back a written file. My GET methods work without a problem.
Here are the errors I'm getting:
xhr.js:166 OPTIONS http://localhost:57429/api/MiniEntity 404 (Not Found)
Access to XMLHttpRequest at 'http://localhost:57429/api/MiniEntity' from origin
'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't
pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested
resource.
Here is my React code:
var apiUrl = "http://localhost:57429/api/MiniEntity";
axios.post(apiUrl, this.state.entitiesToExport).then(response => {
console.log(response.data);
});
Here is my C# API code:
// Post: api/MiniEntity
[HttpPost]
public HttpResponseMessage PostMiniEntities([FromBody] object value)
{
HttpContext.Response.Headers.Add("access-control-allow-origin", "*");
var json = JsonConvert.SerializeObject(value);
System.IO.File.WriteAllText("output.txt", json);
var dataBytes = System.IO.File.ReadAllBytes("output.txt");
var dataStream = new MemoryStream(dataBytes);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
httpResponseMessage.Headers.Add("Access-Control-Allow-Origin", "*");
httpResponseMessage.Content = new StreamContent(dataStream);
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = "output.txt";
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
httpResponseMessage.Content.Headers.Add("Access-Control-Allow-Origin", "*");
httpResponseMessage.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
httpResponseMessage.Headers.Add("Access-Control-Allow-Methods", "POST, OPTIONS");
return httpResponseMessage;
}
All the header stuff is my attempt at allowing access, but it doesn't work.