user3200120
user3200120

Reputation:

Node.js - res.send() never sending message?

For some reason, no matter what I try, my response message is not getting sent. For a short while it was working, then I messed with some code and now it's broken. Anyone know the answer to my tricky little problem?



    exports.listBoth = function(req, res)
    {
        blah.find({name: req.params.name}).count().exec(function (err, count)
        {
            if(err)
            {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            }
            else
            {
                console.log(count);
                if(count >= 1)
                {
                    blah.find({name: req.params.name}).exec(function (err, blah)
                        {
                            res.jsonp(blah);
                        }
                    );
                }
                else
                {
                    res.send('No blah Found');
                }
            }

        });


Upvotes: 1

Views: 13062

Answers (2)

Taehyun Hwang
Taehyun Hwang

Reputation: 260

If you use custom error class like the below example, you could send error message natively with this code

const err = new CustomError('Custom Error...');

...

res.send(err);

err's message included automatically

I searched for implementation of the Error class in 'core-js'

enter image description here

https://github.com/zloirock/core-js/blob/master/packages/core-js/internals/wrap-error-constructor-with-cause.js#:~:text=if%20(message%20!%3D%3D%20undefined)%20createNonEnumerableProperty(result%2C%20%27message%27%2C%20message)%3B

So, if you want message should be displayed in console or delivered by JSON you should use the following code

class CustomError extends Error {
  constructor (message) {
    // super(message)
    super() // avoid message's non-enumerable property

    this.name = this.constructor.name
    this.message = message;

    // needed for CustomError instanceof Error => true
    Object.setPrototypeOf(this, new.target.prototype);

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, this.constructor)
    }
  }
}

Upvotes: 0

Roman Sachenko
Roman Sachenko

Reputation: 668

In order to resolve the issue you have faced with, you need to change your response to send JSON object instead of mentioned string.

You may do something like:

res.send({message: 'No blah Found'});

or

res.status(404).send({success: false, error: {message: 'No blah Found'}});

etc.

So the main point is passing JSON object in order to get it sent correctly.

In some situation you may use res.json() to convert entity automatically, but it will not work correctly with strings.

Upvotes: 2

Related Questions