我已经阅读了一些有关HTTP状态的文章,但仍然不确定为什么要在我的应用程序中指定它们。假设某个用户在尝试登录时提供了错误的密码。在我的快速应用中,我可以通过以下方式发送回复:
res.status(401).json({ message: 'Wrong password' })
Run Code Online (Sandbox Code Playgroud)
要么
res.json({ message: 'Wrong password' })
Run Code Online (Sandbox Code Playgroud)
然后,我的应用程序逻辑基于该 message值。我知道在第二种情况下状态码将会是200 OK,但是我为什么要关心它呢?
很多原因。我头顶上的一些:
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.