I'm trying to log node.js objects on the client. JSON.stringify gives me:
TypeError: Converting circular structure to JSON
util.inspect doesn't seem to produce a string that I can turn back into an object after it's been sent to the client through websockets.
Is there a way to inspect the object on the client side then?
I've stumbled upon this issue many times in the past when trying to JSON.stringify() a Circular structure. Thus, the circular-structure-stringify npm package had been made to circumvent it. Simply put, its usage is similar to JSON.stringify(circular-obj) and can be used like such:
import CircularStructureStringify from 'circular-structure-stringify';
console.log(CircularStructureStringify(THE_CIRCULAR_JSON));
Related
I'm getting a problem in some nodejs servers where string query params get parsed into an array instead of being kept as a string. So something like this https://somedomain.com/test?first=val&token=secret will get parsed on the nodejs server such that the value in params.first is ['val'] instead of 'val' and the value in params.token is ['secret'] instead of 'secret'. What's unusual is that I've seen this in unrelated nodejs servers. One is an aws lambda running in production and the other was a local dev server where I was using express.js with bodyParser. Different codebases for each one. In the past I've run into issues with the qs package due to the way it parses arrays, but this problem seems totally unrelated and I can't seem to find a similar problem reported elsewhere. Does anyone have any ideas what's causing this behavior? Thanks! :)
I eventually figured out that the problem was the url had the same query param multiple times, and the querystring package handles this by creating an array with each value. The package is deprecated so I switched to the recommended URLSearchParams alternative, and I fixed the duplication problem in the url.
I am new to the whole backend stuff I understood that both bodyparser and express.json() will parse the incoming request(body from the client) into the request object.
But what happens if I do not parse the incoming request from the client ?
without middleware parsing your requests, your req.body will not be populated. You will then need to manually go research on the req variable and find out how to get the values you want.
Your bodyParser acts as an interpreter, transforming http request, in to an easily accessible format base on your needs.
You may read more on HTTP request here ( You can even write your own http server )
https://nodejs.org/api/http.html#http_class_http_incomingmessage
You will just lose the data, and request.body field will be empty.
Though the data is still sent to you, so it is transferred to the server, but you have not processed it so you won't have access to the data.
You can parse it yourself, by the way. The request is a Readable stream, so you can listen data and end events to collect and then parse the data.
You shall receive what you asked for in scenarios where you do not convert the data you get the raw data that looks somewhat like this username=scott&password=secret&website=stackabuse.com, Now this ain't that bad but you will manually have to filter out which is params, what is a query and inside of those 2 where is the data..
unless it is a project requirement all that heavy lifting is taken care of by express and you get a nicely formatted object looking like this
{
username: 'scott',
password: 'secret',
website: 'stackabuse.com'
}
For Situation where you DO need to use the raw data express gives you a convenient way of accessing that as well all you need to do is use this line of code
express.raw( [options] ) along with express.json( [options] )
I want to parse interaction message requests coming from Slack. This is what Slack says in their docs:
The body of that request will contain a payload parameter. Your app
should parse this payload parameter as JSON.
That seemed straightforward, so I parsed it like so:
JSON.parse(decodeURIComponent(body.split('=')[1]))
However, in the string-fields of the resulting object, I see pluses instead of spaces:
"There+should+not+be+pluses+here"
What am I doing wrong here?
Took a look at their library here, and it turns out, they use node's querystring.parse().
So the parsing procedure should look like this:
JSON.parse(querystring.parse(body).payload)
I am using socket.io websockets in nodejs. I am trying to stringify the socket object to be able to save it into my database. Here is what I am doing:
socket.on('open-room', function(arg, callback) {
var socketStr = JSON.stringify(socket);
}
But I am getting the following error:
TypeError: Converting circular structure to JSON
If you're looking for a general solution on how to convert an object into a JSON string without encountering a circular structure error (usually, you would do this for logging or debugging), check out the S.O. answer Converting Circular Structure to JSON. If it's not important exactly what the output format is, you can use the built in util.inspect(socket).
If you're doing this for any reason other than logging, be aware that a socket.io websocket can't be serialized/deserialized (you won't be able to recreate a working websocket using the database record).
You might have better luck crafting a more specific JSON object containing only the keys you actually care about, and storing that in the database, rather than attempting to stringify the entire object.
On POSTing data to my expressjs app, this is what I am getting:
node(58287,0x7fff771ad960) malloc: *** error for object 0x7ff8a8600c58: incorrect
checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
Any idea why?
Update:
Here is some code:
Client side:
$.ajax({
url: 'user/' + id,
type: 'POST',
dataType:'JSON',
data: JSON.stringify(data),
success: function(response){
console.log(response);
}
});
Server side:
app.post('/user/:id', function(req,res){
var id = req.params.id;
console.log(data);
});
When I use JSON.stringify on the client side, I am hitting this weird error:
node(58461,0x7fff771ad960) malloc: * error for object
0x7fa861d00e28: incorrect checksum for freed object - object was
probably modified after being freed.
* set a breakpoint in malloc_error_break to debug Abort trap: 6
When I don't use JSON.stringify on the client side, I get 'null' strings on the server side.
Any ideas on what I am doing wrong?
I experienced this same error recently. Here's the fix:
Node.js has had some bugs that cause it to install improperly from source under OS X (see e.g. issue 2061). The good news is that the packaged installer installs it correctly. So, simply uninstall Node, then head to http://nodejs.org/#download and run the Macintosh Installer.
I've reported this bug on the Node issue tracker here.
This is liable to be a bug in nodejs's internals. (Or, if expressjs has any native-code bindings, perhaps expressjs.)
There's no easy way for you to write this kind of bug yourself in JavaScript. If you can reproduce this at will, they'd probably like a bug report. Try to figure out the least amount of code that can reproduce the problem.
I just got this error today, and updating Node.js through MacPorts from 0.8.9_0 to 0.8.10_1 fixed the issue.
It doesn't seem this was specifically adressed though, as bug reports and the changelog don't indicate that (http://blog.nodejs.org/2012/09/25/node-v0-8-10-stable/).
I haven't looked into the cause of these issues (plural - there are clearly at least two bugs somewhere along the line - jquery, node, express), although a summary and workaround are as follows:
When your client side code looks like in your updated question the server obviously shouldn't crash with a malloc error (bug #1), although it is understandable that the query is mistreated, since you're telling jquery to send json and then you send a string.
bug #2 is simply null --> "null" along the pipe. This at least doesn't cause a server crash, because data types match headers (i.e. everyone think we're using json), however someone is converting nulls to strings. My baseless suspicion is that it's express/connect.
Finally, the workaround is simply to wrap your data in a way that manages to be transported, and then unwrap on the server side:
Client side:
$.post({
url: 'user/' + id,
data: {workaround: JSON.stringify(data)}, // no null strings this way
success: function(response){
console.log(response);
}
});
Server side:
app.post('/user/:id', function(req,res){
var id = req.params.id;
var data = JSON.parse(req.body.workaround); // unwrap
console.log(data);
});
If I find time, I'll investigate and try and post a bug report somewhere (it's a problem when you don't know whose fault this is...), please try do this as well.
You are are calling console.log server-side on 'data' which is not defined in the scope of your example.