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

Having trouble calculating the number of days between two dates at this moment

I'm working with a code snippet that involves comparing two dates – a specified date and the current date. However, when trying to calculate the difference in days between these dates, I keep getting either 0 or an unexpectedly large number like "31 ...

Despite implementing cors() in NodeJS, React is still blocking access due to CORS restrictions

Encountering this well-known error message even though I have included app.use(cors()) in my nodejs backend Access to fetch at 'http://localhost:5000/api/v1/visa/getOne/test' from origin 'http://localhost:3000' has been blocked by CORS ...

Issue with MIME handling while utilizing Vue-Router in combination with Express

Struggling to access a specific route in Express, I keep encountering an error in my browser. Additionally, when the Vue application is built, only the Home page and the 404 page seem to work properly, while the rest display a default empty HTML layout. F ...

What is the best way to allocate values within a for loop?

I am in the process of designing an interface for individuals who have no background in programming. My goal is to allow them to input certain details, and then be able to simply copy and paste the code to make everything function seamlessly. Here is a sa ...

Ways to stop custom Mailchimp form from redirecting upon submission

I have integrated a custom Mailchimp signup form into a webpage I am developing. The form works well, but I would prefer to avoid the automatic redirect to a new tab upon submission, which displays a confirmation message from Mailchimp about joining the ma ...

Having trouble sending messages on the server?

Programmer Seeking Help with Adding Data on the Server using JavaScript Stack I am encountering an issue with my javascript code as I am attempting to use the post method to add data on the server-side, but it seems to not be posting successfully. Can ...

Using vue.js to sort comments based on the highest number of votes

Can someone guide me on sorting data (comments) based on the number of votes using vue.js? Much appreciated! data: { comments: [{ title: "Excellent blog post!", votes: 5 }, { title: "Interactive commenting feature in VueJ ...

Working with MongoDB collections in JavaScript to extract and manipulate array data

I have successfully parsed this array using a for loop You can view the results in the console log below. https://i.sstatic.net/zxBna.png When handling role_code in JavaScript, the following code snippet can be used: for (doctor in data.user.userType){ ...

What is the process for developing an interface adapter using TypeScript?

I need to update the client JSON with my own JSON data Client JSON: interface Cols { displayName: string; } { cols:[ { displayName: 'abc'; } ] } My JSON: interface Cols { label: string; } { cols:[ { label:&a ...

What is the method for transmitting a YAML file in the form of a base64 encoded string?

I am attempting to transmit a yaml file as a base64 string in order for this code to function: const response = await octokit.request('GET /repos/{owner}/{repo}/git/blobs/{file_sha}', { owner: 'DevEx', repo: 'hpdev-content&apos ...

Electron triggers MouseLeave event on child elements

Dealing with mouse hover events can be a bit tricky, especially when working with AngularJS in an Electron-hosted app. Here's the HTML template and script I'm using: HTML: <div id="controlArea" (mouseenter) = "onControlAreaEnter()" ...

Error: The method User.generateAuthToken does not exist as a function

UserSchema.prototype.generateAuthKey = async function() { const currentUser = this; const authKey = jwt.sign({_id:currentUser._id.toString()}, 'thisisnewcourse'); return authKey; } const authenticationKey = await User.generateAuthKey ...

Retrieve data from a JSON gist by parsing it as a query string

I have a JavaScript-based application with three key files: index.html app.js input.json The app.js file references input.json multiple times to populate content in div elements within index.html. My goal is to enhance the functionality so that when acc ...

Requesting the user to repeatedly input their birth year until it is less than the current year

Can anyone help me figure out how to display a prompt until the user enters a birth year that is less than the current year? I've tried using a loop in my code, but I'm having trouble getting it right. Any assistance would be greatly appreciated. ...

What is the best way to ensure an observable has finished before retrieving a value?

Looking at the function provided below: public getAssemblyTree(id: number) { .... const request = from(fetch(targetUrl.toString(), { headers: { 'responseType': 'json' }, method: 'GET' })); request.sub ...

Tips for retrieving a child component's content children in Angular 2

Having an issue with Angular 2. The Main component displays the menu, and it has a child component called Tabs. This Tabs component dynamically adds Tab components when menu items are clicked in the Main component. Using @ContentChildren in the Tabs comp ...

Utilizing the power of THREE.ShaderLib.phong while integrating subsurface scattering within ThreeJS

My mesh utilizes a ShaderMaterial with THREE.ShaderLib.phong uniforms. I have successfully linked the map, bump, and specular maps textures. The code snippet below demonstrates this: defines = {}; defines["USE_MAP"] = ""; defines["USE_BUMPMAP"] = ""; defi ...

Converting an array to an object using underscore: a beginner's guide

My array consists of different subjects: var subject = ["Tamil", "English", "Math"]; Now, I want to transform this array into an object, structured like this: [{ "name": "Tamil" }, { "name": "English" }, { "name": "Math" }] ...

Guide to utilizing JavaScript and JQuery for retrieving a PDF from a specific URL and subsequently uploading the file to another website

I have a link to a PDF file: http://www.example.com/HelloWorld.pdf My objective is to download the file using JavaScript/JQuery/AJAX and temporarily store it in the browser, without saving it on the user's machine. Then, I want to POST it to . To ac ...

Challenges Encountered When Working with React.useState()

I am facing an issue where a new row is not appearing after clicking the button. Although the console.log output indicates that the row was added correctly to the tables variable. Another concern I have is why I can see the new row added to the table even ...