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
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, tryJSON.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”.
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:
You can also use
app.use(express.json());
It is convert req.body values in json formate
Example