Home > other >  Is ending responses in Express with a status code always necessary or recommended?
Is ending responses in Express with a status code always necessary or recommended?

Time:03-04

I'm confused about this. I have seen a lot of people ending responses with just res.send();. At the same time, some tend to include a status code, like res.status(422).send();. I understand that this is useful when a user, for example, has sent a request to /log-in/ with data that represents a type different from the one needed and appropriate. In such cases, I'm ending my responses with res.status(422).send();. If I'm expecting a username, but I instead receive an array, it seems to me that such an approach is appropriate. However, if everything is technically alright and the user has just entered a username that does not exist, do I need to include a status code? When such a thing happens, a message under the form will be displayed instead. And res.send("This username does not exist."); is the function I would call. Should I call res.status(401).send("This username does not exist."); instead?

CodePudding user response:

Technically you are not forced to use status codes however it's recommended to follow the best practices.

When the user does not exist return 404 not 401. 401 is unauthorized

When user input is not expected, that's validation error(bad request) and return 400 instead of 422. 422 is used in slightly different scenarios.

Read more about it 400 vs 422

More details about http status codes

CodePudding user response:

Yes, status codes are very important as a good practice I would prefer 404 instead of 401 in your case res.status(404).send("This username does not exist.");

stackOverflowAnswer

Why do we use the status code? To make your debug life easy/ better error handling and to log the error in production to know the severity of the error your application has in case it crashes.

How to Specify statusCode in Node.js

When to use what status code

CodePudding user response:

By default, Express answer all endpoints with 200 unless you didn't specified an endpoint, in this case it will automatically reply with 404. by the way, Express also has res.sendStatus() function that ends the request and sending status

CodePudding user response:

This has to do with your api design. Generally you would be publishing your api specs (Api specification) and there would mention how your client can find out if something is going wrong or going fine.

HTTP Response code are some of easiest way to inform client about outcome of request. So they don't have to go inside the payload of response to check what was outcome. Since most of codes are well know and there is consensus you will write more standard code which works with network elements like proxies, load-balancer etc and understandable developers. Advantages of status codes

  • Related