Search code examples
javascriptjsonnode.js

TypeError: Converting circular structure to JSON in nodejs


I am using request package for node.js

Code :

 var formData = ({first_name:firstname,last_name:lastname,user_name:username, email:email,password:password});

  request.post({url:'http://localhost:8081/register', JSON: formData}, function(err, connection, body) {

exports.Register = function(req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    console.log("Request data " +JSON.stringify(req));

Here I am getting this error :

TypeError: Converting circular structure to JSON

Can anybody tell me what is the problem


Solution

  • JSON doesn't accept circular objects - objects which reference themselves. JSON.stringify() will throw an error if it comes across one of these.

    The request (req) object is circular by nature - Node does that.

    In this case, because you just need to log it to the console, you can use the console's native stringifying and avoid using JSON:

    console.log("Request data:");
    console.log(req);