0

I am trying to make POST and GET requests to a local .NET Core Web API. I learned about the CORS problem for the first time today and I am able to get GET requests to work by simply installing the Google Chrome extension called "Allow-Control-Allow-Origin: *".

However, my POST request fails each time due to the CORS policy. It is so annoying and I can't find an easy or reliable work-around. I am not too considered about making CORS work in every browser. Even if I could get it to work in Google Chrome alone with be a life saver.

I've looked around and there isn't a streamlined solution that has worked for me yet.

My call to the Web API looks like this from within my React App.

axios.post('https://localhost:44395/api/record/create', { Status: "Initiated", Owner: "Peter Porcupine", DateTimeCreated: new Date().getTime(), LastTimeCreated: new Date().getTime(), Comment: { TimeStamp: new Date().getTime(), Text: "Comment sent to API." }})
    .then(response => {
      console.log("Response below from post request");
      console.log(response);
    });

The call returns a 404, and I also get the following error: Access to XMLHttpRequest at 'https://localhost:44395/api/record/create' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I tried to make the POST request using Postman with a similar body and it works and updates my database. I'm certain it isn't an issue related to what body I send the API.

MisterTams
  • 95
  • 2
  • 9
  • 1
    You need to learn how to use CORS. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api – SLaks Jun 17 '19 at 02:10
  • 1
    You need to enable CORS on your server. You can do this by setting the `Access-Control-Allow-Origin` to all `*`. https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work – M.Nar Jun 17 '19 at 02:11
  • 1
    CORS should be solved on the server side. Your sever should be able to serve `OPTIONS` request and should send the header `Allow-Control-Allow-Origin` with the respective value. If you are using somekind of framework, there would be already some piece of code/plugins to enable it. – Panther Jun 17 '19 at 02:12
  • 1
    This answer might help you to enable CORS https://stackoverflow.com/questions/44379560/how-to-enable-cors-in-asp-net-core-webapi – Panther Jun 17 '19 at 02:13

1 Answers1

-1

Your server should be sending response. The header of that response must be changed for CORS to work.

Add these three lines while you send response to client:

context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, 
OPTIONS,DELETE");
context.Response.Headers.Add("Access-Control-Allow-Headers", "Origin, Content-Type, 
Accept");