The `res.send()` function is showing [object object] and I am unable to access any properties

I've just started learning about REST APIs with express. I am encountering a strange issue where the code successfully console logs { name: 'Test', id: 1 } for the user, but when I send the response, it displays [Object object]. Additionally, I am unable to access the user properties directly, but if I use JSON.stringify(user), all the properties are there.

I have included app.use(express.json()) right after the required modules.

const users = []
router.post('/', (req, res) => {
    const newUser = { 
        name: req.body.firstName,  // firstName is the input name in HTML
        id: users.length + 1
    }

    const valid = true;
    if (valid) {
        users.push(newUser)
        res.redirect(`/users/${newUser.id}`)
    }
})

router.get('/:id', (req, res) => {
        const user = users.find(elem => elem.id == req.params.id)
        console.log(user)
        res.send(`GET user with id ${req.params.id} ${user}`)
    })

Answer №1

As @Andreas mentioned, you are trying to convert an Object into a String.

If you need to view an object in string format, consider using the JSON.stringify() method.

Here's how you can modify your approach:

const myObject = { a: 3 }
const myVariable = 4

console.log(`${myVariable} ${JSON.stringify(myObject)}`) // 4 {"a":3}

When incorporating this into your code:

res.send(`GET user with id ${req.params.id} ${JSON.stringify(user)}`)

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

I'm looking for a way to implement a jQuery-style initialization pattern using TypeScript - how can I

My library utilizes a jQuery-like initialization pattern, along with some specific requirements for the types it should accept and return: function JQueryInitializer ( selector /*: string | INSTANCE_OF_JQUERY*/ ) { if ( selector.__jquery ) return select ...

Using both PHP and jQuery to add a class upon changing the URL

I am struggling to implement sorting functionality on my webpage, as the active class is not being added to the selected sorting option... Check out my code snippet below: <ul class="nav nav-tabs"> <li class="menusel active" name="hlavni" on ...

It appears that the JSON format of the HTTP response body returned by Rails is not valid

Currently, in my Rails project, I am utilizing the following method to return a JSON response: def return_json render json: params end Upon inspecting the response using Chrome Developer Tools, everything appears to be correct. However, upon examinin ...

Got a value of `false` for an attribute `closable` that is not meant to be a

Here's the code snippet I have: import { Modal } from "antd"; import styled from "styled-components"; export const StANTModal = styled(Modal)` & .ant-modal-content { border-radius: 20px; overflow: hidden; } `; And ...

Storing dates as collection names is not supported in Firestore

I'm currently facing an issue trying to store stock prices in Firestore. I want the structure to resemble something similar to SQL, like this: const d1 = new Date(); const result = d1.getTime(); console.log('Epochtime',result); database.coll ...

Issue with MVC framework: AJAX query callback function not functioning properly

Struggling with implementing a basic Jquery Ajax callback: Here is my Jquery code snippet: $(document).ready(function () { $('#btnClient').click(function (e) { e.preventDefault(); var txtClient1 = $('#txtCli ...

ReactJs: How useEffect is invoked before onClick function in NextJS

I am facing an issue with a button in my Next project. Here is the code for the button: <Button minWidth={'140px'} onClick={() => exec(scope)} >Save</Button> When this button is clicked, it triggers the following function: c ...

Allowing the contenteditable attribute to function only on a single line of

My app allows users to create different lists, with the ability to edit the name. However, I am facing an issue where if a user types a new name, it should remain on only one line. I tried adding max height and overflow hidden properties, but it only hides ...

JQuery can be used to query a JSON array

Seeking assistance in extracting JSON data from my WordPress site to determine the number of posts with a specific custom field value. Here is an example of the JSON output: {"posts":[ { "id": 21831, "custom_fields": { "us_congress_chamber": [ ...

Inquiry regarding JSON manipulation and serialization techniques

I am facing an issue with passing a List of Skills along with a strongly typed view containing an object Person in my viewmodel. Working with the object Person using Html Helpers like @Html.TextBoxFor(m => m.Person.FirstName) is straightforward and I ca ...

How can I access the parent elements within a recursive directive?

I'm currently implementing a recursive directive called https://github.com/dotJEM/angular-tree to iterate through a model structure like the one below: $scope.model = [ { label: 'parent1', children: [{ ...

Determined Worth of Chosen <Datalist> Option

Currently, I am utilizing an <input type='text'> Element in conjunction with a <datalist> to suggest user names for a form. The functionality is working correctly and all my users are displayed. However, upon form submission, I need ...

Tips for implementing validation in JavaScript

I'm brand new to learning Javascript. Recently, I created a template for a login page and it's working perfectly fine. However, I am struggling with setting up validation and navigation. My goal is to redirect the user to another page if their us ...

npm-bundle encounters an issue with Error: ENOENT when it cannot find the file or directory specified as 'package.json'

npm-bundle is throwing an error that says Error: ENOENT: no such file or directory, open 'package.json' in my NodeJs project. It works fine if I manually create test.js and package.json, then run npm install followed by npm-bundle. However, when ...

Guide for inserting personalized buttons onto a map with the Bing Maps 6.3 Ajax Control

Looking to enhance a Bing Map with custom buttons for more interactive functionality? I'm interested in creating a custom dashboard on the map that would allow users to toggle different information or colors displayed on specific pins or polygons by s ...

Set the background-color of each <td> element to be equal to a value in the array, with each group of three elements having the same

I am trying to color every <td> element in a row of three columns with the same color using the following code: for (var i = 0; itr < $("td").length; i++) { $("td").eq(i).css("background-color", Colors[i]); } However, this code colors each i ...

The client_id from Facebook oauth is not functioning properly to obtain the access token needed to retrieve feeds

I'm currently utilizing the https://graph.facebook.com/oauth/access_token?client_id={app_id}6&client_secret={app's_secret}&grant_type=client_credentials in order to obtain a token that allows me to access and read the feeds from a spec ...

An error occurred with Express and Passport: ['ERR_HTTP_HEADERS_SENT']

Currently, I am diving into an ebook tutorial and have encountered a roadblock in a particular piece of code. The code is designed to take a username and password in JSON format through Insomnia or Postman, and it should return a login success cookie. Howe ...

JavaScript: Creating an array of images from a directory

I've encountered a problem that has proven to be more complex than expected - I am struggling to find resources related to my specific question. My goal is to store 36 images from a folder on my computer into an array using Javascript. Below, you will ...

Tips for accessing and displaying JSON data using jQuery

Data in JSON format: [ { "ID":"25", "Serial":"1", "Purchase_id":"8", "Item":"23", "Unit":"1", "HSN":"84212120", "Quantity":"10", "Purchase_rate":"100", ...