user6002037
user6002037

Reputation:

making POST request using fetch

If not using vanilla js I have always used jQuery to make AJAX requests. Now since React has been taking over, to make AJAX requests there is no need to use the whole jQuery library to make these requests so we are encouraged to use either js' built in fetch method, axios or many others.

I have been trying to make a POST request using fetch. I am able to make it using axis but not fetch.

axios.post('https://reqres.in/api/login', {
    "email": "peter@klaven",
    "password": "cityslicka"
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
}); 

The axios code looks like this, but when I try what I believe to be the same thing using fetch it doesn't work. Can anyone see what I am missing? The values are being posted, but the API is returning an error, so I must be doing something wrong.

var data = {
    "email": "peter@klaven",
    "password": "cityslicka"
}

fetch("https://reqres.in/api/login", {
    method: "POST",
    body:  JSON.stringify(data)
})
.then(function(response){ 
    return response.json(); 
})
.then(function(data){ 
    console.log(data)
});

Upvotes: 6

Views: 24082

Answers (2)

Rmjs
Rmjs

Reputation: 86

Using arrow functions:

fetch('http://myapi.com/user/login', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-type': 'application/json',
    },
    body: JSON.stringify({
      login: login,
      senha: password
    })
  }).then(response => response.json())
  .then((responseJson) => console.log(responseJson))
}).catch(error => console.log(error));

Upvotes: 3

challenger
challenger

Reputation: 2214

 var headers = {
   "Content-Type": "application/json",                                                                                                
   "Access-Control-Origin": "*"
}

try adding the above lines to headers.

var data = {
    "email": "peter@klaven",
    "password": "cityslicka"
}

fetch("https://reqres.in/api/login", {
    method: "POST",
    headers: headers,
    body:  JSON.stringify(data)
})
.then(function(response){ 
    return response.json(); 
})
.then(function(data){ 
    console.log(data)
});

Upvotes: 10

Related Questions