So when a login fails to validate, I currently respong with res.send(401). However I want to send a snippet of text or html along with the error code.
I tried this:
res.write('string');
res.send(401);
but threw an error and my server wouldn't start.
The simplest way of handling errors in Express applications is by putting the error handling logic in the individual route handler functions. We can either check for specific error conditions or use a try-catch block for intercepting the error condition before invoking the logic for handling the error.
The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
sendStatus() Function. The res. sendStatus() function is used to set the response HTTP status code to statusCode and send its string representation as the response body. Parameter: The statusCode parameter describes the HTTP status code.
Express' sendFile() function lets you send a raw file as a response to an HTTP request. You can think of res. sendFile() as Express' static middleware for a single endpoint.
You're mixing Express methods with the native HTTP methods. Since Express' internally uses the native HTTP modules, you should use one or the other.
// Express
res.status(401);
res.send('string');
// or the shortcut method
res.send(401, 'string');
// HTTP
res.writeHead(401);
res.end('string');
From the examples in express docs
res.status(404).send('Sorry, we cannot find that!');
res.status(500).send({ error: 'something blew up' });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With