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

How do I navigate to a different page in Vue.js HTML based on user selection?

Here is my first attempt at writing HTML code: <div class="col-md-4" > <div class="form-group label-floating"> <label class="control-label">Select No</label> <select class="form-control" v-model="or" required=""> ...

Steps for changing a component's properties when the component serves as a property

The scenario I'm facing involves a component that receives a prop named button. This button prop is essentially a Component itself, containing various other props within it. My goal is to override the specific prop called type within this nested struc ...

The client end encountered an issue preventing the saving of a jpeg image

I have a situation where I need to retrieve an image stored on the server and send it to the client using sockets. While I am able to display the received image on canvas, I am encountering difficulties in saving the image to the local disk. I have attempt ...

Angular JS page in its purest form

I have successfully developed a single-page application using AngularJs. However, when I visit the main page of my application hosted on the Heroku server, for a brief moment, all the images and text appear in a raw state at the top left corner of the bro ...

Replicate the form to a new one while concealing the elements and then submit it

Initially, I was working with just one form. Now, I find myself in a situation where I need to utilize a different form which contains the same inputs. This is necessary because depending on the action taken upon submission, different processes will be tri ...

Troubleshooting: Unable to modify value with function in AngularJS

Why can't I change a value using a function in AngularJS? html: <div ng-controler='TestCtrl' id='TestCtrl'> <h1>Test: {{test.name}}</h1> <div ng-hide='showTest'> <div class=&a ...

Does an accepted depiction exist to illustrate the contrast between two JSONs?

Is there an established framework or convention to depict the difference between two JSON documents? Imagine two remote nodes (or a server/client) where each has its own complex JSON data, whose structure is unknown until runtime. One node wishes to send ...

Is it possible to have a div set to close upon loading the page?

Is there a way to have the toggle function set up so that when the page loads, the div being toggled starts out closed? I don't want them to be visible until clicked on. Best regards, Joey <script type="text/javascript> $(document ...

Attempting to conceal image previews while incorporating pagination in Jquery

I'm working on implementing pagination at the bottom of a gallery page, allowing users to navigate between groups of thumbnail images. On this page, users can click on thumbnails on the left to view corresponding slideshows on the right. HTML <di ...

Storing an empty string in a Laravel database: A step-by-step guide

Below is the code snippet from my controller: public function addEmployer(Request $request) { $validator = UserValidations::validateEmployer($request->all()); if ($validator->fails()) { return response(['status' => false ...

What could be the reason for the lack of error handling in the asynchronous function?

const promiseAllAsyncAwait = async function() { if (!arguments.length) { return null; } let args = arguments; if (args.length === 1 && Array.isArray(args[0])) { args = args[0]; } const total = args.length; const result = []; for (le ...

Add a CSS class to the text that is selected within a Content Editable div

Hey there, I'm having an issue where the class is being applied to the button when pressed instead of the selected text. Here's my current code: The button needs to be a div, but it might be causing the problem. I just want the highlighted text ...

How should we provide the search query and options when using fuse.js in an Angular application?

Having previously utilized fuse.js in a JavaScript project, I am now navigating the world of Angular. Despite installing the necessary module for fuse.js, I'm encountering difficulties implementing its search functionality within an Angular environmen ...

Angular restricts the use of the svg namespace in the $sce service for security reasons

I have a project in Angular Material where I am using an md-icon with a specific svg structure: <md-icon class="ic1" md-svg-src='data:image/svg+xml, <svg xmlns="https://www.w3.org/2000/svg" viewBox="0 0 32 32"> <ellipse ry="16" rx=" ...

using outlines for FontAwesome icons in React Native

I am struggling to use the fontAwesome + icon in the middle of a circle as one item. I have tried placing it inside a circle icon, but it doesn't seem to work properly. import IconFA from 'react-native-vector-icons/FontAwesome'; < ...

"Patience is key when waiting for an AJAX response within a jQuery loop

I've been facing difficulties in making this work using the $.Deferred object. Here is a simplified version of the code setup. g_plans = []; $(function(){ // Need to utilize a custom ajax function that returns a promise object var pageLoadPro ...

Tips on inserting javascript to modify the CSS class of a table data cell in a Flask WTF jinja2 table based on the cell's value

I have integrated Flask WTF to showcase the results of a database query. I am seeking a way to modify the cell background color to light red if the value is below 25. I am unsure about where and how to embed the JavaScript code to validate the cell value a ...

The JSON.parse function encounters issues when trying to parse due to a SyntaxError: Unexpected character found after JSON at position 2, causing it to be unable

I've encountered an issue with my JavaScript code when trying to retrieve the value of the details field from JSON data. While all other values are successfully passed to their respective fields, the details field generates the following error: "Unabl ...

What is the best way to extract information from a JSON array using Gson?

Currently, I have obtained a json file with data structured in the following format: [ [ "name1", "age1", "gender1", url1 ], [ "name2", "age2", "gender2", url2 ], ... ] I am looking to parse this data and s ...

What is the best way to find the most commonly used category for a product in a MongoDB collection?

I've been diving into MongoDB and encountered a challenge with my current task. I'm trying to figure out how to determine the most frequently used category in a collection. According to this JSON, the most used category is CIES. My goal is to dis ...