当用户向我的 API 提交无效数据(通常通过 Javascript + JSON)时,我想知道哪个 HTTP response code我应该回复。
我应该返回包含错误的 HTTP 200 响应 - 还是我的服务器应该响应 400 或 500 错误,因为请求实际上由于某些错误数据而未能通过我的验证?
似乎 400 错误是正确的选择,因为“4xx 类状态代码适用于客户端似乎犯了错误的情况”- wikipedia
但是,需要记住的一件事是,大多数人使用像 jQuery 这样的框架,当 AJAX 请求以 200 以外的任何状态代码响应时,它要求您指定备用回调。
最佳答案
400 Bad Request The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
在jquery ajax调用中使用statusCode:
<html>
<head>
<title>jquery testing</title>
<script type="text/javascript" src="jquery-1.6.2.min.js"/>"></script>
<script language="javascript">
$(document).ready(
function(){
$('#linkClick').click(
function(){
$.ajax({
url: 'a.html',
data: {},
type: 'get',
dataType: 'json',
statusCode: {
404:function() { alert("404"); },
200:function() { alert("200"); },
201:function() { alert("201"); },
202:function() { alert("202"); }
},
success: function(data) {
alert( "Status: " + data);
}
});
});
}
);
</script>
</head>
<body>
<a href="#" id="linkClick">click</a>
</body>
</html>
关于ajax - 如果 REST API 方法失败,我应该返回 200、400 还是 500 HTTP 状态消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9345620/