JS API call returns an undefined variable

I am trying to access the dataValues section of a JSON object returned by a function that is invoked through an API call:

exports.findOne = (req, res) => {
    const id = req.params.id;

    Users.findByPk(id)
        .then(data => {
            if(data){
                console.log("data: ", data);
                res.send(data);
            } else {
                res.status(404).send({
                    message: "Cannot find user with id=${id}"
                });
            }
        })
        .catch(err => {
            res.status(500).send({
                message: err.message || "Error retrieving Tutorial with id=" + id
            });
        });
};

When I print out the 'data' variable, this is the output:

findOne:  Login {
  dataValues: {
    ID: 20,
    username: 'phil_swift',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3b3abaaafb0b4aaa5b783a5afa6bbb7a2b3a6eda0acae">[email protected]</a>',
    password: '<ENCRYPTED>',
    account_type: 1,
    token: null,
    token_expiration: null,
    require_password_at_login: false
  },
  _previousDataValues: {
    ID: 20,
    username: 'phil_swift',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f2829a9b9e81859b9486b2949e978a86938297dc919d9f">[email protected]</a>',
    password: '<ENCRYPTED>',
    account_type: 1,
    token: null,
    token_expiration: null,
    require_password_at_login: false
  },
  uniqno: 1,
  _changed: Set(0) {},
  _options: {
    isNewRecord: false,
    _schema: null,
    _schemaDelimiter: '',
    raw: true,
    attributes: [
      'ID',
      'username',
      'email',
      'password',
      'account_type',
      'token',
      'token_expiration',
      'require_password_at_login'
    ]
  },
  isNewRecord: false
}

However, when I make a GET request from the front end, it returns undefined.

const { dataValues } = await httpCommon.get("/" + this.state.user.userID);
console.log("dataValues: ", dataValues);

Why does this happen and how can I solve it?

Answer №1

Shoutout to @codemonkey for sharing this helpful advice with me. His suggestion of substituting res.send(data) with res.json(data) really did the trick.

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

Removing values when disabling a button using JavaScript

Within my code, I have two tables - one for non-clickable teams and another for clickable matches. Check out the image of the tables View the code on my GitHub repository let teams = [ {name: 'Roma', points: 0, wins: 0, draws: 0, loses: ...

What is the best way to retrieve a value from a deeply nested callback function?

I am currently using the mssql npm library and it's functioning well. However, I'm facing difficulty retrieving the recordset returned from the sub-level callback function. Could someone guide me on how to obtain the recordset when dealing with ...

Engage in a Play app featuring AngularJS frontend navigation

Currently, I am using the Play Framework to develop a REST service and I would like the front end to be built with Angularjs in order to make rest calls. I have configured a route provider as follows: angular.module("getAbscencePlans", ["getAbscencePlans. ...

Update Django 3.2 to use AJAX to fetch and display data instead of rendering HTML web pages

I successfully implemented ajax on my website to update the content without refreshing the page. However, I am facing an issue where I can't replace the old content with the new one that is returned. When I use console.log(data), I can see the new HTM ...

Node throws an error of "XMLHttpRequest is not defined" when JSONLoader is used

I'm currently developing a multiplayer game using Three.js, and I need to ensure that client positions are validated on the server side to avoid cheating. To achieve this, I am attempting to load a model on the server with the following code: var THR ...

The jQuery timer I implemented is not showing up properly on my webpage

Here's a look at my HTML: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/boot ...

Tips for accessing arrayList data within a loop in JavaScript and displaying it in an HTML <c: forEach> tag

I have an array list stored inside a javascript code block. I am looking to extract this array list and iterate through it using the html tag <c:forEach>. How can I achieve this? Currently, I am able to display the array list using <h:outputText&g ...

Implementing a Class on Page Refresh in Next JS

I am fairly new to using react and nextjs. How can I insert a script in a component to add a class when the page reloads? The code below doesn't seem to work because the page is not yet rendered when I try to add the class for the body tag. const Mode ...

JavaScript Game Engine - Code Runs Smoothly in the Editor! Encountering Errors in the Inspector?

Issue Resolved in Editor, But Errors Found in Inspector Upon completion of the game development, the document successfully ran in Dreamweaver and TacoHTML. However, when loaded into the w3 Inspector, several errors were detected related to tag styles and ...

Using a SAML token on the client side to access a JSON webservice, following successful login into the website

Currently, I am in the process of developing a website that utilizes a SAML token for single sign-on security measures. Within this site, there is a form containing multiple input fields that are responsible for triggering updates and validation across var ...

How can one variable hold multiple values simultaneously?

Here is some AngularJS code that may be new to you: var deferred = $q.defer(), nextTransClass, prevTransClass; Can anyone explain the purpose of this variable assignment? It's not something I've encountered before. ...

Is this AJAX request properly formatted?

I am attempting to send an array of variables to my CakePHP action for editing purposes. The array is created from the ids of table rows. Below is the javascript code snippet that can be found in my index.ctp file. <script type="text/javascript"> $( ...

What exactly is the purpose of measuring "First Load JS" in the @next/bundle-analyzer tool?

The analysis generated by the NextJS bundle analyzer appears as follows: Page Size First Load JS ┌ λ / 12 ...

Node and Express are facing a dilemma with their routes and functions, leading to a circular reference issue

Seeking advice from experienced programmers: How can I access two variables sent via AJAX post (username, pic) in the users.js route from req.body? I want to use my functions in a file named main.Funcs exported to server.js I'm struggling to extrac ...

angularjs invoking a function within a nested ng-repeat once it's completed

My issue involves 2 nested ng-repeat loops and a boolean variable. The goal is to hide the loading div once all content is rendered, but currently the loading div disappears before that happens. The boolean variable is dependent on a callback function that ...

Streaming live audio through socket io. Need help troubleshooting ALSA shutdown issue

Looking to develop a live audio streaming service using socket.io and ionic 4. On the client side, utilizing cordova-plugin-audioinput and ng-socket-io for Angular. For the server, employing standard npm packages. Node version: 10.16.0 ...

What could be the reason for encountering the error message "Attempting to access an undefined HTML property"?

I've been working on a simple counter to practice closures in JavaScript, and I'm struggling with an error that I can't seem to solve. I thought assigning the variable elem to the id of canv would do the trick, but clearly something isn&apos ...

Neglectful TypeScript null checks overlooking array.length verification

When TypeScript is compiled with strict null checks, the code snippet below does not pass type checking even though it appears to be correct: const arr: number[] = [1, 2, 3] const f = (n: number) => { } while (arr.length) { f(arr.pop()) } The comp ...

How come I am encountering a syntax error when trying to access an object item by its index?

I'm curious as to why this particular scenario is occurring: var obj = { 0:"bla", 1:"blabla" } For some reason, when I try to access obj.0, an error is returned and I can only use obj[0]. Why is that the case? ...

Tips for closing a (Javascript iframe) on an ASP.NET platform

I am trying to close an iframe using a button click, but my current code is not working as expected: <td> <a href="utility.htm" toptions="group = links, shaded = 1, type = iframe, effect = fade, width = 900, height = 900, layout = quicklook"> ...