skip to Main Content

I am learning NodeJs , currently I have just made a middleware function which will send the entire
req object as value of a single key-value pair in json object (I know it is very long ) , but just for learning purpose I did it.

Now I know that req is a object in itself and the value must be a string , so I tried to convert it :-

This is my code

function prod (req, res) {
    console.log("This is a body of Req :- " , req );
 
    // const x = JSON.stringify(req);            // Method 1  // throws error of TypeError: Converting circular structure to JSON
    
   // const  x = String(req)                   // Method 2  // displays [object object]  
  
   // const  x = req.toString()                 // Method 3   // displays [object object] 

    res.status(200).json({"Request": `${x}`});
}
module.exports = prod

Now I tried these 3 methods as mentioned one by one, but none of them gave desired result.
Method 1 shows TypeError: Converting circular structure to JSON whereas other 2 methods displays it as [object object].
However in the console.log() line , entire req is printed porperly. Can anyone please tell me why is it not happening in the response & also how can I send the entire req in json body of res

2

Answers


  1. The request and response objects in Express aren’t simple JSON objects like you expect; they’re classes with methods that aren’t serializable. Hence the “converting cyclical structure to JSON” error.

    The variable you’re looking for is probably req.body, so instead of stringifying the request itself, try JSON.stringify(req.body). That should do the trick.

    Also keep in mind that HTTP GET requests don’t have bodies attached typically, so if the route you’re building is for a GET request it may come out as “undefined”.

    Login or Signup to reply.
  2. Express.js express.json() Function

    The express.json() function is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.

    Syntax:

    express.json( [options] )
    

    You can also use app.use(express.json());
    It is convert req.body values in json formate

    Example

    const express = require('express');
    const app = express();
    const PORT = 3000;
    
    app.use(express.json());
    
    app.post('/', function (req, res) {
    console.log(req.body.name)
    res.end();
    })
    
    app.listen(PORT, function (err) {
    if (err) console.log(err);
    console.log("Server listening on PORT", PORT);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search