1

I created a webapi in ASP.NET Core, and I need to consume it using React, the web api works normally, if I use curl or postman among others, it works normally. The problem starts when I'm going to use React, when I try to make any requests for my API with js from the problem.

To complicate matters further, when I make the request for other APIs it works normally, this led me to believe that the problem was in my API, but as I said it works with others only with the react that it does not. I've tried it in many ways.

The API is running on an IIS on my local network

Attempted Ways

Using Ajax

$ .ajax ({
    method: "POST",
    url: 'http://192.168.0.19:5200/api/token',
    beforeSend: function (xhr) {
      xhr.setRequestHeader ("Content-type", "application / json");
    },
    date: {
      name: 'name',
      password: 'password'
    },
    success: function (message) {
        console.log (message);
    },
    error: function (error) {
        / * if (error.responseJSON.modelState)
            showValidationMessages (error.responseJSON.modelState); * /
            console.log (error);
    }
  });

Using Fetch

const headers = new Headers ();
    headers.append ('Content-Type', 'application / json');

    const options = {
      method: 'POST',
      headers,
      body: JSON.stringify (login),
      mode: 'cors' // I tried with cors and no-cors
    }

    const request = new Request ('http://192.168.0.19:5200/api/token', options);
    const response = await fetch (request);
    const status = await response.status;
    console.log (response); * /
    // POST adds a random id to the object sent
    fetch ('http://192.168.0.19:5200/api/token', {
    method: 'POST',
    body: JSON.stringify ({
      name: 'name',
      password: 'password'
     }),
    headers: {
      "Content-type": "application / json; charset = UTF-8"
    },
    credentials: 'same-origin'
    })
  .then (response => response.json ())
  .then (json => console.log (json))

Using Request

var request = new XMLHttpRequest ();
    request.open ('POST', 'http://192.168.0.19:5200/api/token', true);
    request.setRequestHeader ('Content-Type', 'application / json; charset = UTF-8');
    request.send (login);

ERRORS

Console enter image description here

Network tab enter image description here

When I do this without being change the content type to JSON it works because the API returns saying that it is not a valid type.

You Nguyen
  • 9,961
  • 4
  • 26
  • 52

3 Answers3

2

Apart from allowing CORS in you .NET configuration. You also need to return 200 OK for all OPTION requests.

Not sure how it's done in .NET but just create a middleware that detects the METHOD of the request, and if it's OPTIONS, the finish the request right there with 200 status.

Borjante
  • 9,767
  • 6
  • 35
  • 61
  • 1
    This is correct, though more precisely, the status code can be any 200-209 status code — it doesn’t have to only be 200. A lot of servers return 204 for OPTIONS. See also https://stackoverflow.com/questions/46026409/what-are-proper-status-codes-for-cors-preflight-requests/46028619#46028619 – sideshowbarker Oct 04 '18 at 21:53
0

Well I had the same issue and it seems that you need to add the action to the HttpPost attribute in the controller.

Here is an example.

    [HttpPost("[action]")]
    public void SubmitTransaction([FromBody] SubmitTransactionIn request)
    {
        Ok();
    }
Dharman
  • 30,962
  • 25
  • 85
  • 135
Diego Bascans
  • 1,083
  • 1
  • 6
  • 14
-1

Try like this

 public void ConfigureServices(IServiceCollection services)
 { 
     services.AddCors();
 }

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
        app.UseCors(option => option.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials());

        app.UseAuthentication();
        app.UseMvc();
 }
Nisfan
  • 750
  • 6
  • 10