Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send a string alongside an error code with express?

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.

like image 319
user1816679 Avatar asked Nov 14 '13 01:11

user1816679


People also ask

How do you handle errors in Express?

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.

What does next () do in Express?

The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

How do I send a status code in response Express?

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.

What is Express sendFile?

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.


2 Answers

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');
like image 113
hexacyanide Avatar answered Sep 17 '22 14:09

hexacyanide


From the examples in express docs

res.status(404).send('Sorry, we cannot find that!');
res.status(500).send({ error: 'something blew up' });
like image 45
Bulkan Avatar answered Sep 19 '22 14:09

Bulkan