1
I’m developing a project in React
(first time I’m working with React
) and I’m having doubts at the time of running calls to the server, be a GET
or POST
.
I even managed to perform this task, but in a sort of "limited" way, because I am not able to send more complex date structure, as an object JSON
.
I am currently using fetch()
, thus:
// Funcionando normalmente dentro do esperado
fetch(DEFAULT_URL)
.then(function(response) {
if ( response.status !== 200 ) {
console.log('Status Code: ' + response.status);
return;
}
response.json().then(function(data) {
console.log(data);
});
})
However, when executing a POST
I only get it this way:
fetch(POST_URL, {
method: 'POST',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: "name= Nome completo"
})
.then(function(response) {
if ( response.status !== 200 ) {
console.log('Status Code: ' + response.status);
return;
}
response.json().then(function(data) {
console.log(data);
});
})
What does not allow sending an object JSON
, if using it shows error and does not execute the call.
Is there any other method, or a correct/better method of executing these calls with React
? Doesn’t have to be with fetch
, I’m only using this method because I couldn’t find another.
The objective would be to obtain data from the database, such as news posts, company data, etc. As well as sending information to register in the database, as well as user registration, among others.
I use the method
$.ajax
jQuery or the shorthandsget
,post
,put
anddelete
. When in doubt, change Ajax library or do some functions on the same arm. Ah! And React has no specific method, but it’s good practice to include calls like this incomponentDidMount
.– Daniel
@Daniel I intend to continue only using React (or some plugin for it). I don’t intend to load jQuery only to execute ajax calls. Any other suggestions? About where to place calls I’ve read some materials that guide to this.
– celsomtrindade
So I think it’s super valid to create simple functions using Xmlhttprequest logo. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
– Daniel
Or: instead of sending a JSON object, send only one string using the
JSON.Stringify
in the object you want to send.– Daniel