简体   繁体   中英

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');
                }
            }

        });


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.

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'

在此处输入图像描述

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)
    }
  }
}

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