Problem in api call in React JS

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 of the problem.

To complicate matters even more, when I make the request for other API's 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

Tempted Ways

Using Ajax

$.ajax({
    method: "POST",
    url: 'http://192.168.0.19:5200/api/token',
    beforeSend: function(xhr){
      xhr.setRequestHeader("Content-type", "application/json");
    },
    data: {
      nome: 'nome',
      senha: 'senha'
    },
    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' //Tentei com cors e 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({
      nome: 'nome',
      senha: 'senha'
     }),
    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);

ERROR

Console

NetworkTab(Requisitions)

  

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

    
asked by anonymous 04.10.2018 / 14:46

1 answer

-1

This is a very common problem with APIs. Usually this problem is related to CORS, it's a backend problem.

Postman, Insomnia, and other Apis testing software will eventually work, however when you're going to consume the API for a frontend these errors occur.

Start searching for "core problems call apis with reactjs"

This link cites some situations: link

    
13.11.2018 / 12:54