admin管理员组文章数量:1135140
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
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
Share Improve this question edited Mar 2, 2022 at 6:37 Rohìt Jíndal 27.2k15 gold badges77 silver badges132 bronze badges asked Nov 24, 2014 at 9:11 Hitu BansalHitu Bansal 3,13712 gold badges54 silver badges89 bronze badges 4- 1 Check your data structure. stackoverflow.com/questions/4816099/… – GillesC Commented Nov 24, 2014 at 9:14
- 1 I am not able to get from here. can u pls tell me what changes i need to made in above code – Hitu Bansal Commented Nov 24, 2014 at 9:18
- 4 Does this answer your question? How can I print a circular structure in a JSON-like format? – KyleMit ♦ Commented Jul 14, 2020 at 20:02
- lol none of the answers working... – Dobromir Kirov Commented Jun 28, 2024 at 6:02
19 Answers
Reset to default 111JSON 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);
I also ran into this issue. It was because I forgot to await for a promise.
I was able to get the values using this method, found at careerkarma.com
Output looks like this.
I just run this code in the debugger console. Pass your object to this function.
Copy paste the function also.
const replacerFunc = () => {
const visited = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (visited.has(value)) {
return;
}
visited.add(value);
}
return value;
};
};
JSON.stringify(circObj, replacerFunc());
Try using this npm package. This helped me decoding the res structure from my node while using passport-azure-ad
for integrating login using Microsoft account
https://www.npmjs.com/package/circular-json
You can stringify your circular structure by doing:
const str = CircularJSON.stringify(obj);
then you can convert it onto JSON using JSON parser
JSON.parse(str)
I forgotten to use await keyword in async function. with the given systax
blogRouter.put('/:id', async (request, response) => {
const updatedBlog = Blog.findByIdAndUpdate(
request.params.id,
request.body,
{ new: true }
);
response.status(201).json(updatedBlog);
});
Blog.findByIdAndUpdate should be used with the await keyword.
use this https://www.npmjs.com/package/json-stringify-safe
var stringify = require('json-stringify-safe');
var circularObj = {};
circularObj.circularRef = circularObj;
circularObj.list = [ circularObj, circularObj ];
console.log(stringify(circularObj, null, 2));
stringify(obj, serializer, indent, decycler)
If you are sending reponse , Just use await
before response
await res.json({data: req.data});
It's because you don't an async response For example:
app.get(`${api}/users`, async (req, res) => {
const users = await User.find()
res.send(users);
})
I was also getting the same error, in my case it was just because of not using await
with Users.findById()
which returns promise, so response.status().send()/response.send()
was getting called before promise is settled (fulfilled or rejected)
Code Snippet
app.get(`${ROUTES.USERS}/:id`, async (request, response) => {
const _id = request.params.id;
try {
// was getting error when not used await
const user = await User.findById(_id);
if (!user) {
response.status(HTTP_STATUS_CODES.NOT_FOUND).send('no user found');
} else {
response.send(user);
}
} catch (e) {
response
.status(HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR)
.send('Something went wrong, try again after some time.');
}
});
This is because JavaScript structures that include circular references can't be serialized with a"plain" JSON.stringify.
https://www.npmjs.com/package/circular-json mentioned by @Dinesh is a good solution. But this npm package has been deprecated.
So use https://www.npmjs.com/package/flatted npm package directly from the creator of CircularJSON.
Simple usage. In your case, code as follows
import package
// ESM
import {parse, stringify} from 'flatted';
// CJS
const {parse, stringify} = require('flatted');
and
console.log("Request data " + stringify(req));
Came across this issue in my Node Api call when I missed to use await
keyword in a async
method in front of call returning Promise. I solved it by adding await
keyword.
AxiosService({
method: 'POST',
url: '/products',
data: {
name: productNumber,
number: productNumber,
description: productDescription,
type: category,
price: 0,
},
})
In my case I made mistake in the payload data when making request. By mistake I was setting description as e.target instead of e.target.value when taking input.
I came across this issue when not using async/await on a asynchronous function (api call). Hence adding them / using the promise handlers properly cleared the error.
I was missing .toArray()
when making a call to a MongoDB collection to retrieve multiple documents.
This was throwing the error:
doc = await database.find({ "type": ctx.params.type });
This was the fix:
doc = await database.find({ "type": ctx.params.type }).toArray();
Here's a link to the documentation about it: https://www.mongodb.com/docs/manual/reference/method/cursor.toArray/
If an object has a different type of property like mentioned in the above image, JSON.stringify() will through an error.
For mongodb
so if you are getting errors while fetching data from MongoDB then the problem is async
previously
app.get('/users',(req,res,next)=>{
const user=chatUser.find({});
if(!user){
res.status(404).send({message:"there are no users"});
}
if(user){
res.json(user);
}
})
After
app.get('/users',async(req,res,next)=>{
const user=await chatUser.find({});
if(!user){
res.status(404).send({message:"there are no users"});
}
if(user){
res.json(user);
}
})
Edit May 22, 2023
I think it is an error which need to be fixed not a feature which is needed. I have faced this issue and tried following things. Hope it helps.
The reference does not have resolved value till the time, we are going to use it. In this case, I have awaited the response, by adding await keyword and checking whether I am returning proper value from the function.
In the second case when I faced this issue I had a json like,
{ obj1: "sample1", obj2: "sample2", obj3: obj3 }
or,
{
obj1: "sample1",
obj2: obj1
}
in this case, the value of any of the key in object is again depended on some other key, which was growing the json object recursively. Here, I fixed this dependency of one key on another to resolve it.
Try this as well
console.log(JSON.parse(JSON.stringify(req.body)));
TypeError: Converting circular structure to JSON in nodejs:
This error can be seen on Arangodb when using it with Node.js, because storage is missing in your database. If the archive is created under your database, check in the Aurangobi web interface.
本文标签: javascriptTypeError Converting circular structure to JSON in nodejsStack Overflow
版权声明:本文标题:javascript - TypeError: Converting circular structure to JSON in nodejs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736760040a1951494.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论