I'm developing a project in React
(the first time I'm working with React
) and I'm having doubts when running calls to the server, either GET
or POST
.
I even managed to perform this task, but in a somewhat "limited" way, because I'm not able to send more complex date structure, such as a JSON
object.
I'm currently using fetch()
, like this:
// 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, running a POST
I can only do this:
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 a JSON
object, if it uses it it presents an error and does not execute the call.
Is there any other method, or a correct / best method to execute these calls with React
? It does not have to be with fetch
, I'm only using this method because I could not find another one.
The goal would be to get data from the database, such as news posts, company data, etc. As well as sending information to register in the database, such as user registration, among others.