When it comes to making AJAX requests, I used to rely on jQuery in the past. However, with the rise of React, there is no longer a need to include the entire jQuery library for this purpose. Instead, it is recommended to use JavaScript's built-in fetch method, axios, or other alternatives.
I recently attempted to make a POST request using fetch but encountered some difficulties. While I was able to achieve the desired result with axios, I couldn't replicate the same success with 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 code snippet above shows how axios successfully makes the POST request. However, when trying to do the same with fetch, I faced an issue where the API returned an error. It seems like something might be missing from my fetch implementation.
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)
});