问题
Lets say I have a single-page web application with a list of items where a user can click on an item to view more info about it. The actual item info is loaded asynchronously, using an AJAX GET request to the URL http://www.example.com/item/[id] and is displayed upon loading.
The question is, what to do if the item with the given id doesn't exist? Right now, the request returns status code 200, but the actual content indicates that the item doesn't exist. This seems like a bad idea so I wanted to make it return a status code that would indicate the request failed in a sense, since the item doesn't exist (it would also, for example, allow me to catch it in a fail handler in jQuery's ajax function).
Is this good practice (returning status code 200 only when the item actually exists in the database) and, if so, which status code would be the best to use in this situation?
回答1:
Yes, you are right to want to use a failure status code, not a 200 OK. 404 Not Found would be ideal in this case. (There is also 410 Gone for an item which used to exist.)
Link to spec, or Google "HTTP status codes" for far more resources.
回答2:
Yes, it's a good idea to return 200 status code only when your object exists. When your item does not exist you should return a 404 error code.
More information here
来源:https://stackoverflow.com/questions/25868596/restful-ajax-which-http-status-code-for-item-not-found