sending a POST request with fetch

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)
});

Answer №1

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

Include the above code snippet into your headers.

var data = {
    "email": "john@example.com",
    "password": "securepassword123"
}

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)
});

Answer №2

When it comes to using arrow functions in JavaScript, you can achieve concise and elegant code:

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));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on maintaining and hiding the vertical scrollbar when a popup is open, alongside the navigation bar positioned at the top of the page

After reviewing this pen, my goal is to create a popup that maintains access to the navigation bar (hence avoiding Bootstrap's Modal). However, I am facing the challenge of keeping the scrollbar visible while preventing scrolling in the background whe ...

When an Ajax post request is made, the data being sent is appended to the JSON response

Having a dilemma with my ajax call: $.ajax({ url: '/assets/functions.php', type: 'POST', data: { "functionCall": "get-uploads", "type": type }, dataType: 'json', success: function (data ...

Function that returns an array

Hey there, wondering about variable scope in closures! I've come across a lot of questions on this topic but haven't found the solution to my issue. Here's the code snippet: var teams = []; var players = []; var getRoles = function(roleL ...

What's going on with the background color? It doesn't seem

I have incorporated Bootstrap into my html code and I am attempting to modify the background color of a div when the screen resolution changes from large to medium or small. Even though I have added a class, the change does not reflect when adjusting the ...

Check input validations in Vue.js when a field loses focus

So I've created a table with multiple tr elements generated using a v-for loop The code snippet looks like this: <tr v-for="(item, index) in documentItems" :key="item.id" class="border-b border-l border-r border-black text ...

Having trouble with your mobile dropdown menu not responding to clicks?

I'm having trouble getting a dropdown menu to work on the mobile version of my website. When I click on the dropdown menu image, it's supposed to appear, but it's not working as expected. JSFiddle: https://jsfiddle.net/xfvjv184/ Included ...

Using npm-installed cesium for the web browser is a straightforward process that involves importing

Exciting news - Cesium is now available on npm! Once I've run npm install cesium in my project, all the codes are placed inside the node_modules folder. In the introductory hello world example of Cesium, it imports cesium similar to this: <script ...

invoke a function upon successful completion of an ajax call in a datatable

Can we trigger a JavaScript function after a successful AJAX call in a datatable? Here is the code I am attempting to use: var dataTable = $('#app-config').dataTable( { "bAutoWidth": false, ...

inconsistent firing of mousedown events

On my webpage, I am using the following JavaScript code: $("#attach-body").mousedown(function (event) { //alert(event.button); switch (event.button) { case 2: event.preventDefault(); event.stopPropagation(); break; default: ...

The conditional statement to check for an empty object does not trigger any actions

My goal is to display a success message once users successfully register without any errors. I have an errors reducer object in Redux that stores errors sent from the backend. The logic is set up so that if the errors object is empty, it shows the success ...

Resource loading unsuccessful: server encountered a status of 500 (Internal Server Error)

I'm struggling to figure out why I keep getting an Internal Server Error when trying to call a web service in my HTML page using JavaScript and Ajax. Here is the error message: Failed to load resource: the server responded with a status of 500 (Int ...

Using React hooks and Typescript: I was expecting to see an assignment or function call, but instead, an expression was

After working as a React developer for quite some time, my workplace recently introduced Typescript, which I am still getting familiar with. I implemented a custom hook for managing cookies, but the function it returns is generating an error. Here's ...

I desire to perform a specific task when there is a modification in the path using react router framework

Though I am mindful of it. props.history.listen((location, action) => { console.log("when route changes",location); }) However, I need to implement it in a slightly different way. For instance, let's cons ...

Updating a textbox with JQuery AJAX when the text in another textbox changes

Whenever I type something into an input field with the id "textbox1", I want to update another input field with the id "textbox2" accordingly. This is the code I started with: $("#textbox1").keyup(function(){ $.ajax({ type: "POST", ...

Is there a way to pause and await the completion of an axios post request within a different axios interceptor?

Here are my axios interceptors: instance.interceptors.request.use( (config) => { const accessToken = localStorage.getItem("access_token"); const auth = jwt_decode(accessToken); const expireTime = auth.exp * 1000; co ...

How can I retrieve the width of a responsive React element during its initial rendering phase?

In my React project, there is a component called ResultList which is used to display products in a gallery format. The challenge I'm facing is determining the appropriate number of products to show per row based on the available width for the ResultL ...

Output a message to the Java console once my Selenium-created Javascript callback is triggered

My journey with Javascript has led me to mastering callback functions and grasping the concept of 'functional programming'. However, as a newcomer to the language, I struggle to test my syntax within my IntelliJ IDE. Specifically, I am working on ...

Error receiving parameter in express route callback function

At the moment, I have been working with a number of routes in Express. Some routes are quite lengthy and tend to look like this: router.get('/api/comments', function(req, res, next){ Comment.find({"user": req.payload._id}).exec(function(err,co ...

Is there a way to retrieve the ID from a span and convert it into a string format?

let wordSpan = '<span class="we w_o_r_d_s" id="we" contenteditable="false">we</span>' console.log(wordSpan.id); console.log(wordSpan.attr('id')); console.log(wordSpan.getAttribute('id')); let newDiv = document.c ...

Exploring the spread of jquery/ajax assurances within the Durandal framework

Utilizing durandal, I have a base controller that handles server calls. Each specialized controller for different use cases utilizes the base controller to make the server call. Within the base controller, the following code is present: self.call = functi ...