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
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.– Marconi
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
– Marconi
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)
– Victor