简体   繁体   中英

“Maximum call stack size exceeded” when sending Json with Node.js

I'm using the ajax-request package to send Json data via a post request in my Node.js application. The relevant code snippet looks like this:

logMessage : function(url, message, next) {
  var d1 = message["sender"];
  var d2 = { id: message[sender"]["id"], name: message["sender"]["name"], email: message["sender"]["email"] };
  console.log(d1); // Both outputs look 
  console.log(d2); // exactly the same
  request.post({ url: url, headers: {}, data: d1 }, function (error, response, body) {
    //Check for error
    if(error){
      next(null, {}); // I'm not worried if the logging fails
    }
    //Check for right status code
    if(response.statusCode !== 200){
      next(null, {}); // I'm not worried if the logging fails
    }
    next(null, {})    // All good
  });
}

The problem is that I get a RangeError: Maximum call stack size exceeded . The message object definitely doesn't contain any circular references, and the message is neither that large nor that nested. The call works fine when I use dummy data or drill down to a basic data type, ie, the following works fine

  • data: { 'test': [1, 2, 3]}
  • data: message['sender']['name'] <-- this is a string value
  • data: message['sender']['email'] <-- this is a string value

However, data: message['sender'] already fails although it only contains an object with two simple strings.

The workaround data: JSON.stringify(message) would work, but I still like to understand what the issue is.

EDIT: I've added d1 and d2 as to objects that should be the same, and the console.log outputs are look indeed exactly the same. However, data: d2 is working, while data: d1 is not

EDIT2: JSON.parse(JSON.stringify(message)) as another workaround does the job as well. I guess my message object is not what I thought it would be.

The ajax-request module is likely failing at serializing the object. You do realize that message is not sent as an object, it has to be converted to a string format to be sent. Also I am not sure that it's possible to serialize that data as there is no form input that can have nested names.

You can try using a more tested module like request or just use JSON.

It might be a bad workaround, but at least it works, so I put it as an answer in the hope it might help someone else as well:

data: JSON.parse(JSON.stringify(message))

I simply convert the message object to a string and parse it back to a Json object. No idea why that works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM