Home > Software engineering >  Why Do I Get [object Object] at Request in ExpressJS
Why Do I Get [object Object] at Request in ExpressJS

Time:09-11

Sending 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");

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);

console:

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

I Even Tried req.query & body-parser, But i still get [object Object] or undefined

CodePudding user response:

Because both are objects... You probably wanted to use req.body and/or JSON.stringify() on the object.

enter image description here

CodePudding user response:

body-parser is now deprecated, but from Express v4.16 no additional module is necessary, you can just use the built-in middleware:

app.use(express.json());

After that, depending on the data you want to get from the Request object (req), 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}`);
  • Related