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

Issue with Jest while testing a React component library that has been bundled without the React library

I have extensive experience building React applications and decided to create a React Component library. After researching different approaches, I chose to use Webpack and Babel for bundling without including React itself in the library. This decision was ...

Fix for fixed scrolling in the navigation bar

Having a website that receives traffic from different countries, including Portugal and other non-English speaking places, I decided to add a translation option. However, I encountered an issue with Google's translate feature which displays a banner a ...

Deep Dive into TypeScript String Literal Types

Trying to find a solution for implementing TSDocs with a string literal type declaration in TypeScript. For instance: type InputType = /** Comment should also appear for num1 */ 'num1' | /** Would like the TSDoc to be visible for num2 as well ...

When incorporating ajax in conjunction with a django form, an error arises indicating "Please choose a valid option. It should not be one of the choices provided."

I am a beginner in Django. Currently, I am using simple AJAX to dynamically update the choice field semester. It updates based on the selection of the course. However, I encounter an error when submitting the form which says Select a valid choice. The sele ...

Submitting information to an HTML page for processing with a JavaScript function

I am currently working on an HTML page that includes a method operating at set intervals. window.setInterval(updateMake, 2000); function updateMake() { console.log(a); console.log(b); } The variables a and b are global variables on the HTML page. ...

ng-change not firing when selecting from ng-options list

I am struggling with this code snippet <select ng-model="trabajadores.orderSelected" ng-options="excel for excel in trabajadores.csv.result[1]" ng-change="console.log('changed')"> </select> Despite my best ...

When integrating react-router 5 and redux 7, there is an issue where the state is not being reset when navigating to a new route using react-router's <Link

My current setup includes the following versions: `"react-router": "^5.2.0",` `"react-router-domreact-router": "^5.2.0",` I'm unsure if my setup is compatible with React-router 5 as I was using a version prior ...

Is it possible to modify the CSS injected by an Angular Directive?

Is there a way to override the CSS generated by an Angular directive? Take, for instance, when we apply the sort directive to the material data table. This can result in issues like altering the layout of the column header. Attempting to override the CSS ...

Ways to change the chart type in ApexCharts

I'm seeking a way to change the chart type of an existing ApexCharts that has already been rendered. After reviewing the methods, I attempted to use the updateOptions() method, but encountered the error: Uncaught TypeError: Cannot read property &apos ...

The array does not store the ObjectId

I'm trying to implement the favoriting feature following a tutorial, but I'm encountering issues with making it work. Any assistance would be greatly appreciated. Thank you! UserSchema: var UserSchema = new mongoose.Schema({ username: {type ...

Syntax error: Your code encountered an unexpected closing curly brace

Here is the code snippet I am working with: <?php session_start();?> <!DOCTYPE html> <html> <head> <title>Narcis Bet</title> <meta charset="utf-8"> <link rel="stylesheet" href="css/style.css" type="text/css"&g ...

Passing data from getServerSideProps to an external component in Next.js using typescript

In my Index.js page, I am using serverSideProps to fetch consumptions data from a mock JSON file and pass it to a component that utilizes DataGrid to display and allow users to modify the values. export const getServerSideProps: GetServerSideProps = async ...

Canvas Frustratingly Covers Headline

Several months ago, I successfully created my portfolio. However, upon revisiting the code after six months, I encountered issues with its functionality. Previously, text would display above a canvas using scrollmagic.js, and while the inspector shows that ...

Top method for organizing Vue JS elements

I am looking to integrate a search feature on my website using Vue 2, where the search functionality will be applied to components generated from a JSON file upon page load. The JSON file contains the keywords I want to utilize for the search - specifical ...

JavaScript: What's the best way to update the URL in the address bar without triggering a page refresh?

Similar Question: How can I use JavaScript to update the browser URL without reloading the page? I've observed websites like GMail and GrooveShark altering the URL in the address bar without having to refresh the entire page. Based on my understa ...

Looking for a solution to dynamically fill a list in JQuery with data from a JSON file. Any suggestions for troubleshooting?

Currently, I am utilizing a JSON file to fetch Quiz questions. In my approach, each question is being stored in an array as an object. The structure of the question object includes 'text' (the actual question), 'choices' (an array of po ...

Utilizing JavaScript to trigger a series of click events on a single button in order to

I am working on implementing a click event for a checkbox that will add and remove CSS classes using the "classList.toggle" method. Specifically, I want the checkbox to toggle between adding the "xyz" class on the first click, and then adding the "abc" cla ...

Setting the state to an array of objects in React: A beginner's guide

Currently, I am developing a flashcard application using React. To store the data entered by the user, I have initialized my state as an array of objects that can hold up to 10 terms and definitions at a time: state = { allTerms: [ { ...

The event listener for browser.menus.onClicked is dysfunctional in Firefox

Currently, I am in the process of developing my own Firefox extension and I have encountered an issue with adding a listener to an onclick event for a context menu item. manifest.json { "manifest_version": 2, "name": "My exten ...

What is the preferred approach in JavaScript: having a single large file or multiple smaller files?

Having a multitude of JavaScript files loaded on a single page can result in decreased performance. My inquiry is this: Is it preferable to have individual files or combine them into one JavaScript file? If consolidating all scripts into one file is the ...