Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 449
Hitu Bansal Avatar asked Nov 24 '14 09:11

Hitu Bansal


People also ask

How do you resolve converting circular structure to JSON?

The "Converting circular structure to JSON" error occurs when we pass an object that contains circular references to the JSON. stringify() method. To solve the error, make sure to remove any circular references before converting the object to JSON.

What is circular structure in JSON?

A circular structure is an object that references itself. To be able to stringify such objects, developers can utilize the replacer parameter in the stringify() method, making sure the function that is being passed in, filters out repeated or circular data.

What is Stringify in JSON?

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.


2 Answers

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); 
like image 129
Scimonster Avatar answered Oct 02 '22 21:10

Scimonster


I also ran into this issue. It was because I forgot to await for a promise.

like image 21
Satya Prakash Avatar answered Oct 02 '22 20:10

Satya Prakash