Problem calling api in React JS

Asked

Viewed 1,085 times

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 use React, when I try to make any request for my problem js API.

To complicate even more, when I request other API’s works normally, it led me to believe that the problem was in my API but as I said it works with others only with React that does not. I’ve tried so many ways.

The API is running on an IIS on my local network

Tried 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);

MISTAKES

Console inserir a descrição da imagem aqui

Aba Network (Requests) inserir a descrição da imagem aqui

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

  • What back-end technology do you use? You need to configure CORS on back-end to accept requests from other domains.

  • Check it out: https://answall.com/questions/312129/como-enviar-uma-requisi%C3%A7%C3%A3o-post-using-Axios-e-asp-net-core-web-api

  • If you can attach your code please, it is possible that I will enable Cors for you. In addition, to work with API calls, the React community uses Axios a lot (https://github.com/axios/axios)

1 answer

-1

This is a very common problem with Apis. Usually this problem is related to CORS, is a problem in the backend.

Postman, Insomnia and other API testing software end up working but when you consume the API by a frontend these errors occur.

Start searching for "core problems call Apis with reactjs"

This link cites some situations: https://www.c-sharpcorner.com/article/fetching-data-using-web-api-in-react/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.