The ajax client is encountering an undefined response, but it is correctly processed when accessed through the

I am in the process of setting up an ajax client with a dummy server for testing purposes. I have successfully resolved the cors issue, but now I am facing a problem where the response from the ajax client is showing as undefined. Interestingly, when I access the same URL directly through a browser, it displays the object correctly.

// Dummy Server-Side Code
var express = require('express');
var router = express.Router();
var cors = require('cors');
router.use(cors());

var data = [
    {"id": 1, "message": 'first object'},
    {"id": 2, "message": 'second object'},
    {"id": 3, "message": 'third  object'}
];

router.get('/', (req, res, next) => {
    console.log("Building response body");
    res.json(data);
});


// Client-Side Code
function fetcher() {
    console.log("Fetching from: " + rootUrl + arrayEndpoint);
    fetch(rootUrl + arrayEndpoint, {
        mode: "cors",
        method: "GET",
        headers: {
            "Content-Type": "application/json"
        }
    })
        .then((response) => {
            console.log(response);
            console.log("Response: " + response.body);
        })
        .catch((error) => {
            console.log("Error: " + error);
        });
}

The response printed to the console of the client:

Response { type: "cors", url: "https://angry-badger-63.localtunnel.me/getArray/", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, bodyUsed: false }
undefined

And on the browser:

[{"id":1,"message":"first object"},{"id":2,"message":"second object"},{"id":3,"message":"third  object"}]

It seems like the server-side code is functioning correctly since it sends the expected data to the browser. However, there appears to be an issue with the ajax client that I can't quite figure out. Any insights into what might be wrong with it would be greatly appreciated.

Answer №1

After reading SLak's comment, I realized that fetch does not have resp.body as I had assumed. That was a major oversight on my part.

This led me to discover another issue - when using resp.json() to handle the response, it actually returns a promise which I wasn't properly handling. It seems that parsing the response with .json() or .text() always results in a promise. Although I'm still struggling to get the array correctly, here is an updated snippet to parse a generic JSON object:

//client.js
function fetcher() {
    console.log("fetching from: " + rootUrl + arrayEndpoint);
    fetch(rootUrl + arrayEndpoint,{
        mode: "cors",
        method: "GET",
        headers: {"Content-Type": "application/json"}
    })
        .then(function(response) {
            response.json()
                .then(function (data) {
                    console.log(data);
                });
        })
        .catch(error => console.log("error:" + error));
}


//server.js
var express = require('express');
var router = express.Router();
var cors = require('cors');
/* GET users listing. */
router.use(cors());

var data = {"1":{"id":1, "message": 'first object'},
  "2":{"id":2, "message": 'second object'},
  "3":{"id":3, "message": 'third object'}};

router.get('/', function(req, res, next) {
  console.log("building response body")
  console.log(data)
  res.json(data);
});

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

Creating JSON arrays with JavaScript and jQuery

User Information var Users=[{"Id":1,"FirstName":"John"},{"Id":2,"FirstName":"Emily"}] Call Information var CallInfo=[{"Id":1,"PercentageCalls":"22 %","TotalTime":"60:24 minutes","PercentageTime":"0 %","AvgTime":"0:22 minutes"},{"Id":2,"PercentageCa ...

`Can you teach me how to dynamically load HTML elements using input JSON data?`

What is the best way to iterate through an input array of objects? I currently have data for only 2 people included. However, there are more than 50 people's information in the input and I need to loop through all of them. Here is a sample code snip ...

Issue with loading CSS and JavaScript following a GET request

I initially used express and the render function to display different pages on my website. However, I've now decided to switch to vanilla JavaScript instead. The objective is to load the HTML file along with all the necessary JS and CSS files. Below i ...

Error message while running jQuery 3.2.1: issues with UL and LI

I have a link that displays the desired outcome Despite using jquery version 3.2.1, when I insert my code into Dreamweaver cc 2018, it fails to work. On my jsfiddle, the selection is sorted alphabetically, but on my web page it is not. var mylist = $( ...

Issue with Vuex: currentUser state not persisting after page refresh

I'm currently working on a Vue.js SPA that utilizes Rails 6 API as the backend and Vue-cli (legacy webpack template). After signing in a user, everything seems to be functioning correctly. I can view the user details, it updates my setCurrentUser mut ...

Is it possible for jQuery datepicker to choose a date over a decade in the past?

Recently, I encountered an issue with jQuery-UI's datepicker where it was restricting me to select birthdays only within the last 10 years. This basically meant that users older than 10 years couldn't be accommodated :) I attempted to override t ...

The PHP form is causing an error: Notice - Trying to convert array to string

I am currently working with a basic form that leads to the following code for processing purposes. include("connect.php"); $items = array_key_exists('equipment', $_POST) ? $_POST['equipment'] : ''; if(!empty($items)) { ...

"Encountering an issue with the Foreach function in nextjs when iterating through

I attempted to iterate through each character in a String, but the SPANS are not displaying. What could I be doing incorrectly? export default function Work() { const logoText = "The future starts here."; return ( <div className=& ...

Changing the CSS property from "display: none" to "display: block" using JavaScript causes all the div elements to overlap

My issue involves several radio inputs where clicking one should reveal a hidden div containing information. However, when this div appears, it overlaps with the footer instead of staying positioned between the footer and radio input as intended. I am str ...

Even with e.preventDefault, the anchor link still opens in a new tab on the browser

I am dealing with an ajax call that triggers a REST API to return a list of all names, as well as another REST API that matches those names. For instance: /list returns: list1, list2, list3 and /api/list1.json returns: JSON data for list1.. Currently, ...

Invoking a function that is declared in a fetch request from an external source beyond the confines of the fetch itself

I am currently struggling with calling a function that is defined inside an API Fetch response function. My code sends an API fetch request to the GitHub API to retrieve a repository tree in JSON format. The problem arises when I try to call a function def ...

Utilizing HTML, CSS, and JavaScript to dynamically add and remove a class from

I've been struggling with a specific issue in my 9-button grid. When I click on a button and it changes color to orange, if I click on another button, both buttons remain orange. What I want is for only one button at a time to be orange - when a new b ...

Send back a JsonResult containing a collection of objects from an MVC controller

In my MVC controller, I have a straightforward method: [HttpPost] public JsonResult GetAreasForCompany(int companyId) { var areas = context.Areas.Where(x => x.Company.CompanyId == companyId).ToList(); return Json(areas); } Here is the structure ...

find all the possible combinations of elements from multiple arrays

I have a set of N arrays that contain objects with the same keys. arr[ {values:val1,names:someName},   {values:val2,names:otherName}, ] arr2[   {values:valx,names:someNamex}, {values:valy,names:otherNamey}, ] My goal is to combine all possible c ...

Customizing App (directory) elements in next.js 13

Imagine having this directory organization: https://i.stack.imgur.com/Hd5gu.png Is there a method for loading the component from the custom folder instead of the default one in the app folder? In case the custom folder does not have that component, can t ...

JavaScript can be used to create dynamic frames within a

Can anyone help identify the issue in my code? frame 1 <script type="text/javascript"> var Clicks = 0 ; function AddClick(){ Clicks = Clicks + 1; document.getElementById('CountedClicks').innerHTML = Clicks ; } localStorage.setItem(' ...

Converting SVG with an external PNG file embedded into a standalone PNG format using Node

Does anyone know of a node package that can convert an svg file to a png, including external images embedded within the svg code like this? <?xml version="1.0" encoding="utf-8"?> <svg viewBox="0 0 120 120" height="120" width="120" xmlns="h ...

The automated test locator in Angular using Protractor is failing to function

I am facing a challenge with my angular web application as there are some elements that are difficult to interact with. One specific element is a checkbox that needs to be checked during testing: ` <div class="row form-group approval_label"> < ...

Generating and displaying a JSON response

I am having trouble displaying a response on the screen using an AJAX request script with a post method and body value. Here is my code: $('#my-form').submit(function () { $.ajax({ url: 'https://apiurl.com/users', ...

Generate a new span element within a div element programmatically using Vuex

I have integrated an existing web application developed using vue.js. Below is the code snippet: function () { var e = this, t = e.$createElement, n = e._self._c || t; return e.messag ...