4

When I connect to my Express 4 node.js websocket server from my client and try to log req, the whole program just gets stuck. It still accepts new connections and executes it to the same console.log, but then gets stuck. I am trying to figure out what req contains, but this way of figuring it out doesn't seem to work.

app.use(function (req, res, next) {
    console.log("middleware");
    var session = req.session;
    console.log("session: " + JSON.stringify(session));
    console.log("req non json: " + req);
    console.log("req: " + JSON.stringify(req));  //stuck
    return next();
});
Waltari
  • 1,052
  • 1
  • 30
  • 64
  • 2
    It's probably not stuck but throwing an exception, as you most likely cannot stringify `req` due to circular references. Try `console.log('req:', req)`. – robertklep Jul 24 '15 at 08:03
  • Thanks that worked, but how is "console.log('req:', req)" different from "console.log("req: " + req);" ?? – Waltari Jul 24 '15 at 08:29
  • 1
    Using `+` stringifies `req`, using it as a separate argument will make `console.log()` use [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options). – robertklep Jul 24 '15 at 08:30
  • @Waltari it is string concatenation. The req object is appended to 'string' first. – Muhammed Basil Jul 24 '15 at 08:53

2 Answers2

6

As Gemtastic said the req just can't be stringified. You can use a custom function to stringify your request with all the data you need. Should be something like this:

const reqData = JSON.stringify({
      headers: req.headers,
      method: req.method,
      url: req.url,
      httpVersion: req.httpVersion,
      body: req.body,
      cookies: req.cookies,
      path: req.path,
      protocol: req.protocol,
      query: req.query,
      hostname: req.hostname,
      ip: req.ip,
      originalUrl: req.originalUrl,
      params: req.params,
});
Adam Genshaft
  • 756
  • 10
  • 22
1

What's happening here is that you're trying to stringify req, an object not stringifiable.

console.log() accepts many arguments in the constructor, if you supply one argument and use + what's happening is that you're trying to pass two strings into console.log() stringifying or .toString() the object instead of printing the object's content.

I'm gonna try and explain what you should do and why:

console.log("string as argument one", [object]) This is the desired effect you want, internally console.log() will understand that you want to print the string and the object's content and not the .toString() which most often is [Object object] or doesn't exist (not all objects have a .toString() since they can be created out of different prototypes).

Gemtastic
  • 6,253
  • 6
  • 34
  • 53