Reputation: 2807
I've read some articles about HTTP statuses, and i'm still not sure why i should specify them in my app. Let's say a user provided wrong password while trying to login. In my express app i can send response in those ways :
res.status(401).json({ message: 'Wrong password' })
or
res.json({ message: 'Wrong password' })
Then my application logic is based on the message
value.
I understand that in the second case the status code is going to be 200 OK
, but why should i care about it ?
Upvotes: 2
Views: 110
Reputation: 163262
Many reasons. A few off the top of my head:
Caching. 2xx
responses are cacheable by default. You shouldn't be sending a 200
response for an error or it may look to the user like they can never login!
Compatibility with client libraries. It sure is nice to be able to use things that are standards compliant, so you can maybe do a .catch()
and show the user an error rather than having a ton of custom logic to figure out whether the response was good or not.
Status codes also come from other code in the chain. You're often not just talking to your app, but usually a proxy on your end. And then, there may be several proxies between the client and you. Why should your client code have to figure out both your application-level signalling and the status code signalling when they can be one of the same? Ask someone with satellite internet... they'll tell you about what a pain intermediate proxies can be when people don't follow the standards.
Automatic error logging. Surely you use some system to track errors in your system, right? If you use standard HTTP response codes, they can be categorized automatically.
Upvotes: 7
Reputation: 399
There are plenty of reasons. At the highest, clearest level - it's accessibility / universality.
Consider a few scenarios:
2xx
responses are cached; so on and so forth.401 Not Authorized
than it is to rely on wrong password
in your message field. What if you change the string, even just adding a .
or captilizing something?Upvotes: 1
Reputation: 664185
You need to care about HTTP because you are relying on it for your application to work. Using the appropriate HTTP verbs and status codes is necessary for this, allowing e.g. middleware or browser caches to do their work. You don't want your error message to be cached.
Upvotes: 1