Revamp your jQuery Ajax call by utilizing the Fetch API

Below is my attempt to convert the following jquery's AJAX call using the fetch function:

 const sendingData = {...}     

 $.ajax({
   url: "/api/data/getuser",
   type: "GET",
   data: sendingData ,
   dataType: 'json',
   ContentType: 'application/json',
   success: (data) => {
     console.log('SUCCESS')
     console.log(data)
     this.setState({
       isFetching: false,
       data: data.user
     })
   },  
   error: (err) => {
     console.log(err)
     this.setState({isFetching: false})
   } 
})

I'm trying to rewrite it with the fetch method. I attempted this code snippet:

fetch("/api/data/getuser", {
  method: "GET",
  data: data,
  dataType: 'json',
  ContentType: 'application/json'
}).then((resp) => {
  console.log(resp)
}).catch((err) => {
  console.log(err)
})

Although the server should return an object containing user information, instead, the response object received is as follows:

Response {type: "basic", url: "http://localhost:3001/api/data/getuser", redirected: false, status: 200, ok: true, …}
body: ReadableStream
locked: (...)
__proto__: Object
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:3001/api/data/getuser"
__proto__: Response
}

Answer №1

To retrieve the response body in parsed JSON format, you should utilize resp.json().

For more information, refer to https://developer.mozilla.org/en-US/docs/Web/API/Body/json

fetch("/api/data/getuser", {
  method: "GET",
  data: data,
  dataType: 'json',
  ContentType: 'application/json'
})
.then((resp) => {
  return resp.json();
})
.then((userData) => {
  console.log(userData);
})
.catch((error) => {
  console.log(error)
})

Answer №2

Additionally, headers need to be included.

fetch("/api/data/getuser", {
  body: data,
  headers: {
    'Content-Type': 'application/json'
  }
})
.then((response) => {
  return response.json();
})
.then((userData) => {
  console.log(userData);
})
.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

`My jquery mobile application fails to trigger the pageinit or ready events`

My website consists of 3 PHP pages: one index page and two subpages for sales and products. The index page has links to these subpages. When I click on the sales link, it is supposed to load sales data either on pageinit or document ready. However, no code ...

Edit data within an Angular table on-the-fly

Currently, I am in the process of developing a dynamic table that may have an unknown number of columns and rows. My goal is to incorporate inline editing with inline templates using ng-include. The first issue at hand: I am faced with the challenge of u ...

What's the best way to execute multiple actions within a single gulp task?

Is there a way to execute multiple actions within one gulp task? I have tried using event-stream's merge feature following the example in How to perform multiple gulp commands in one task, but it doesn't work properly when combined with the del p ...

Disabling Commands using Discord JS Commando in a guild

Curious about something. Will Discord JS Commando disable a command only within a specific server (guild) or globally across all servers? ...

Positioning a div above a Bootstrap navbar that disappears when scrolling

I am currently using bootstrap to design a website, and I am attempting to create a div that would initially appear above the navbar on an unscrolled webpage. However, once the user starts scrolling, I want this div to disappear and have the navbar fill it ...

Navigating Through Secondary Navigation with Ease

In my React project, I am developing a mega-menu styled dropdown navigation. As a functional component, I am utilizing the useState hook to manage the state and control the display of sub-navigation items. The functionality of the dropdown is operational, ...

Enhance the editing capabilities of the Json data form

https://i.stack.imgur.com/YZIjb.png My goal is to enhance a form for editing json data by moving beyond the typical <textarea /> tag and making it more user-friendly. Are there any tools available that can help improve the form's usability? Add ...

In what way does Codesandbox create a resizable grid layout for components?

I am looking for guidance on implementing resizable windows like those in CodeSandbox and VS Code using React. How does CodeSandbox achieve this functionality? Could someone help me get started in the right direction? ...

Transmitting information securely and remotely between two online platforms

I own two websites and another at When a user clicks on something on example1.com, I want it to trigger a popup from example2.com. Then, I need to send some data back to example1.com using GET parameters and be able to detect it using jQuery or JavaScrip ...

Is there a way to circumvent the eg header along with its contents and HTML code using JavaScript?

I have a script in JavaScript that is designed to replace the content of data-src attribute within each img tag with src. However, I am facing an issue where this script interferes with the functionality of a slider located in the header section. The sli ...

Develop a dynamic grid in EXT JS 4 with columns determined during execution

I'm currently working with EXTJS4 and I have a tree that shows classes (classname) on one side. When a user clicks on a class name, I would like to display the objects associated with that class in a separate grid. These objects will be retrieved from ...

Utilizing jQuery with live content to determine dimensions as required

Within my web application, I have a page that dynamically retrieves a view with both HTML and JavaScript. The JavaScript is responsible for rendering a chart into the retrieved view. The problem arises because the chart library I am utilizing (flot) necess ...

Troubleshooting: Node.js Express Server GET Handler Failing to Function

Recently, I've been attempting to build a GET request handler in Express.js. Here's the snippet of code I've put together: // include necessary files and packages const express = require('./data.json'); var app = express(); var m ...

Creating a custom ID for a Firebase POST request

Is it possible to assign a custom ID in Firebase when using the POST method? For example: { "users": { "user_one": { "username": "jdoe", "password": "123" } } } I'm currently working on a Vue.js project and I want to save ...

Posting an array using jQuery's AJAX feature

Consider the following JavaScript array structure: testarr = new Array(); testarr[0] = new Array(); testarr[0]["#FFFFFF"] = "White"; testarr[0]["#FFFFFF"] = new Array(); testarr[0]["#FFFFFF"]["#FFFFFA"] = "A"; testarr[0]["#FFFFFF"]["#FFFFFB"] = "B"; test ...

Material Angular table fails to sort columns with object values

Currently, I am in the process of developing a web application using Angular Material. One of the challenges I have encountered is displaying a table with sorting functionality. While sorting works perfectly fine on all columns except one specific column. ...

Is there a method to track changes in the DOM made by AngularJS?

I'm currently exploring ways to detect changes in the DOM caused by AngularJS using jQuery. Despite setting up AJAX and history change listeners, I am still unable to successfully capture these alterations. Is there a way to achieve this? ...

Loading jQuery on an ajax request

The loader is working with the code now, but it is not replacing and calling the URL. The ajax url call should be placed within searchable. <button onclick="myFunction()">LOAD</button><br /><br /> <div class="spinner bar hide" ...

Retrieve the selected value from a radio button

I am attempting to display the chosen value in an input field when a radio button is selected. However, the functionality seems to be broken when I include bootstrap.min.js. You can find the code on JSFiddle. $('input:radio').click(function() ...

Combining lodash flow with multiple arguments

In my code, I have two functions that will be added in a lodash flow: function normalizeFields(fields) { return _.mapValues( fields, function(value) { return { 'content': value }; }); } function mergeModelAndFields(model, normal ...