Javascript Ajax 调用的 JSON 响应的正确状态代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5021403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:16:56  来源:igfitidea点击:

Proper status codes for JSON responses to Ajax calls?

javascriptajaxjsonhttphttp-status-codes

提问by anonymous coward

My project is returning JSON to Ajax calls from the browser. I'm wondering what the proper status code is for sending back with responses to invalid (but successfully handled) data submissions.

我的项目正在将 JSON 返回到来自浏览器的 Ajax 调用。我想知道发送回无效(但已成功处理)数据提交的正确状态代码是什么。

For example, jQuery has the following two particular callbacks when making Ajax requests:

例如,jQuery 在发出 Ajax 请求时有以下两个特定的回调:

success: Fired when a 200/2xx status code is delivered along with the response.

success:当 200/2xx 状态代码与响应一起传递时触发。

error: Fired when 4xx, 5xx, etc, status codes come back with the response.

error:当 4xx、5xx 等时触发,状态代码随响应返回。

If a user attempts to create a new "Person" object, I send back a JSON representation of the newly created object upon success, thus giving javascript access to the necessary unique ID's for the new object, etc. This, of course, is sent with a 200 status code.

如果用户尝试创建一个新的“Person”对象,我会在成功后发回新创建对象的 JSON 表示,从而让 javascript 访问新对象所需的唯一 ID,等等。当然,这会被发送带有 200 状态代码。

If a user submits malformed or invalid data (say, an invalid/incomplete "name" field), I would like to send back the validation error messages via JSON. (I don't see why this would be a bad thing).

如果用户提交格式错误或无效的数据(例如,无效/不完整的“名称”字段),我想通过 JSON 发回验证错误消息。(我不明白为什么这会是一件坏事)。

My question is:in doing so, should I send a 200status code, because I successfully handled their invalid data? Therefore, I'd be using the jQuery successcallback, but simply check for errors...

我的问题是:这样做时,我是否应该发送200状态代码,因为我成功处理了他们的无效数据?因此,我将使用 jQuerysuccess回调,但只需检查错误...

Or, should I use a 4xxstatus code, perhaps 'Bad Request', because the data they sent me is invalid? (and thus, use the errorcallback to do the necessary client-side notifications).

或者,我应该使用4xx状态代码,也许是“错误请求”,因为他们发送给我的数据无效?(因此,使用error回调来执行必要的客户端通知)。

采纳答案by MPV

I agree with the 400 Bad Request response.

我同意 400 Bad Request 响应。

For inspiration you could have a look at how Twitter (widely used JSON service) does this: https://dev.twitter.com/overview/api/response-codes

为了获得灵感,您可以查看 Twitter(广泛使用的 JSON 服务)如何执行此操作:https: //dev.twitter.com/overview/api/response-codes

CodeTextDescription

CodeText描述

  • 200OK- Success!
  • 304Not Modified- There was no new data to return.
  • 400Bad Request- The request was invalid or cannot be otherwise served. An accompanying error message will explain further. Requests without authentication are considered invalid and will yield this response.
  • 401Unauthorized- Missing or incorrect authentication credentials. Also returned in other circumstances (for example, all calls to API v1 endpoints return 401).
  • 403Forbidden- The request is understood, but it has been refused or access is not allowed. An accompanying error message will explain why. This code is used when requests are being denied due to update limits . Other reasons for this status being returned are listed alongside the response codes in the table below.
  • 404Not Found- The URI requested is invalid or the resource requested, such as a user, does not exists. Also returned when the requested format is not supported by the requested method.
  • 406Not Acceptable- Returned when an invalid format is specified in the request.
  • 410Gone- This resource is gone. Used to indicate that an API endpoint has been turned off.
  • 420Enhance Your CalmReturned when an application is being rate limited .
  • 422Unprocessable Entity- Returned when an image uploaded to POST account / update_profile_banner is unable to be processed.
  • 429Too Many Requests- Returned when a request cannot be served due to the application's rate limit having been exhausted for the resource. See Rate Limiting .
  • 500Internal Server Error= Something is broken. Please post to the developer forums with additional details of your request, in case others are having similar issues.
  • 502Bad Gateway- Twitter is down or being upgraded.
  • 503Service Unavailable- The Twitter servers are up, but overloaded with requests. Try again later.
  • 504Gateway Timeout- The Twitter servers are up, but the request couldn't be serviced due to some failure within our stack. Try again later.
  • 200OK- 成功!
  • 304Not Modified- 没有要返回的新数据。
  • 400Bad Request- 请求无效或无法以其他方式提供服务。随附的错误消息将进一步解释。未经身份验证的请求被认为是无效的,并将产生此响应。
  • 401Unauthorized- 身份验证凭据丢失或不正确。在其他情况下也会返回(例如,对 API v1 端点的所有调用都返回 401)。
  • 403Forbidden- 请求被理解,但被拒绝或不允许访问。随附的错误消息将解释原因。当请求由于更新限制而被拒绝时使用此代码。返回此状态的其他原因列在下表中的响应代码旁边。
  • 404Not Found- 请求的 URI 无效或请求的资源(例如用户)不存在。当请求的方法不支持请求的格式时也返回。
  • 406Not Acceptable- 在请求中指定无效格式时返回。
  • 410Gone- 这个资源没了。用于指示 API 端点已关闭。
  • 420Enhance Your Calm当应用程序受到速率限制时返回。
  • 422Unprocessable Entity- 无法处理上传到 POST 帐户 / update_profile_banner 的图像时返回。
  • 429Too Many Requests- 由于资源的应用程序的速率限制已耗尽而无法提供请求时返回。请参阅速率限制。
  • 500Internal Server Error= 东西坏了。如果其他人遇到类似问题,请将您的请求的其他详细信息发布到开发者论坛。
  • 502Bad Gateway- Twitter 已关闭或正在升级。
  • 503Service Unavailable- Twitter 服务器已启动,但请求已超载。稍后再试。
  • 504Gateway Timeout- Twitter 服务器已启动,但由于堆栈中的某些故障而无法为请求提供服务。稍后再试。

回答by Wirde

I would send a '400 Bad Request' header back in response with information in json of what went wrong. Then catch the event with jquerys $.ajaxError() event handler and parse the error message i got in return to deliver good feedback to the end user.

我会发送一个“400 Bad Request”标头作为响应,并在 json 中提供错误信息。然后使用 jquerys $.ajaxError() 事件处理程序捕获事件并解析我收到的错误消息,以向最终用户提供良好的反馈。

You can read more about the ajaxError event handler here!

您可以在此处阅读有关 ajaxError 事件处理程序的更多信息!