What Causes [object Object] to Appear in ExpressJS Request?

Sending a GET Request:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = () => {
    console.log(`response-text -> ${xhttp.responseText}`);
}
xhttp.open("GET", "http://localhost:3001/get/", true);
xhttp.send("hello world");

Working with ExpressJS :

const express = require('express');
const app = express();
const cors = require('cors');

app.use(cors({origin: '*'}))
app.get('/get/', (req, res) => {
    res.send(`Your Request -> ${req.params}`);
})

app.listen(3001);

Debugging in console:

response-text -> Your Request -> [object Object]

Despite trying req.query and body-parser, the output remains as either [object Object] or undefined

Answer №1

body-parser has been deprecated, but starting from Express v4.16, you no longer need an additional module. You can simply use the built-in middleware:

app.use(express.json());

From there, depending on the data you wish to retrieve from the Request object (req), you can access the corresponding property:

  • Request Path Parameters (GET '/get/:param' with value as :param):
res.send(`Your Request -> ${req.params.param}`);
// or
res.send(`Your Request -> ${req.params['param']}`);
  • Request Query Parameters (GET '/get?param=value'):
res.send(`Your Request -> ${req.query.param}`);
// or
res.send(`Your Request -> ${req.query['param']}`);
  • Request Body (GET '/get/' with a body):
res.send(`Your Request -> ${req.body}`);

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

Converting a curl command into an AJAX request

Here's the curl bash command that I'm currently using: curl -d "username=UID&password=PASS" http://localhost:8080 I'm looking to convert this into an ajax request in Java Script. Could you guide me on how to do that? This is what I ha ...

Cannot be iterated upon when utilizing the find ObjectId operation

I'm attempting to locate a specific document in my MongoDB and then update its integer value using a find query. I am utilizing $in because I used an array to search for each element within it, but when I used ObjectId it is throwing an error: bloo ...

AngularJS Cascading Dropdowns for Enhanced User Experience

There is a merchant with multiple branches. When I select a merchant, I want another dropdown list to display the data from merchant.branches. The following code does not seem to be fixing the issue: <label>Merchant:</label> <select ng-if= ...

Combining Extjs combo with autocomplete functionality for a search box, enhancing synchronization capabilities

When using autocomplete search, I've encountered an issue. If I type something and then make a mistake by deleting the last character, two requests are sent out. Sometimes, the results of the second request come back first, populating the store with t ...

Caching of audio files in React streaming is enabled

My dilemma lies in the fact that despite creating a new file in the back-end, the <PlaySound /> component continues to play the old sound file rather than the updated one. Although the sound file maintains the same name and path, its content differs. ...

Adjust the background shade of a div according to the color attribute retrieved from a JSON data source

Looking at this snippet, I'm tasked with changing the color of the "header" div to match the color provided in the JSON data. The code snippet is as follows: $("#dropdown").change(function() { $("#header").css("background-color", $(this).val()); }).c ...

Cannot extract the 'name' property from 'e.target' because it is not defined

I encountered an error message stating that I cannot destructure the property 'name' of 'e.target' because it is undefined within the createform() method. Despite highlighting the line causing the error, I am still unable to comprehend ...

Invoke the app.js function within the Node.js route file

Within app.js, there is a function that I am attempting to invoke from a routes file. This is just a simplified example. app.js var express = require('express'); var app = express(); var customFunction = function() { return 'result&apo ...

What could be causing the inability to retrieve the HTML content of $(window['iframeName'].document.body) when I modify the .attr('src') method?

Why isn't it functioning $(window['iframeName'].document.body).html() ...properly when I update the .attr('src')? When I initially set the src attribute of the iframe to a URL upon creating the page, this code $(window['i ...

Develop a carousel component using Vue.js

I'm currently working on a dashboard that needs to display cards, but I'm running into an issue. I want only four cards visible at a time, and when you click the arrow, it should move just one step to the next card. For example, if cards 1-4 are ...

Obtaining the value of a command argument with JavaScript in ASP.NET

<asp:LinkButton ID="lnkprogress" runat="server" class="label label-info" BackColor="#589FC2" CommandArgument='<%#Eval("BookingId")%>' OnClientClick="jk();" >In progress</asp:LinkButton> This LinkButton is present in a repeat ...

Trouble displaying options in Angular JS ng-repeat

I'm currently facing an issue with populating data from a database onto a web page. Despite my efforts, I haven't been able to get it to work as intended: <div ng-controller="AnalyzerController"> <select id="Listbox" ng-model="Listof ...

Mishap with ShareThis.com Social Media Buttons Hit Counter

Having some issues with the hitcount on my social media share buttons. Whenever I "Share" the page on Facebook, it gets counted as a "Like" when I refresh the page. <span class='st_facebook_hcount' st_title='$videoTitle' displayText ...

Exploring the implementation of custom middleware in Node.js

Recently, I created a custom middleware that attempts to retrieve the cookie from the client. Here is how I declared it: function auth(req, res, next) {} However, in order to access the cookies from the request, I understand that I need to incorporate ano ...

The Protractor test scripts are running with lightning speed, outpacing the webpage loading time

Seeking guidance on automating an angular js website with login functionality. Need to click on the sign-in link and enter username and password, but facing issues with script execution speed being faster than page load. Here is my approach for handling th ...

Align the final date row with every image block to avoid discrepancies

Could you please advise me on whether to use a table structure or div structure for creating HTML code for the image attached? I also want to ensure that the last date row is synchronized with a specific color block image. How can I achieve this effect? ...

Launching shuttles using HTML and JavaScript

I've been working on an HTML code with JavaScript for a platform validation project. Over the last couple of weeks, I've been diligently coding and testing to ensure everything runs smoothly. However, my code suddenly stopped responding, leaving ...

When implementing tooltips in Apexchart's JavaScript, the y-axis second does not appear in the chart

Typically, when I append data to the second y-axis as an array, it works perfectly. However, for some reason, when I try to append a collection to the data, it no longer shows with two y-axes simultaneously. I even tried adding x and y as the Apex documen ...

Converting an HTTP request and incorporating a success function in Typescript and Angular2

I am working on a http request: private getValues() { this._watchlistElements.map(v => this.http.get('http://localhost/getValue/' + v.xid) .subscribe(res => { this._values.push(res.json()); })); }; When the request ...

Utilizing AngularJS to bind form fields with select boxes to enable synchronized data. Modifying the selection in the dropdown should dynamically

Currently, I am working on an input form that involves a select with various options. Depending on the user's selection, three additional fields need to be populated accordingly. For instance: If the user picks Option1, then the three other fields s ...