I can't use json to make a Post request to my web api using react

余生颓废 提交于 2019-12-13 04:19:55

问题


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

Network tab

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.


回答1:


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.




回答2:


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();
    }

If anyone know why, please help to present a more complete anwser.




回答3:


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();
 }


来源:https://stackoverflow.com/questions/52647909/i-cant-use-json-to-make-a-post-request-to-my-web-api-using-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!