随着 Web 应用的不断发展,RESTful API 成为了前后端通信的重要手段,但是在开发的过程中难免会遇到一些问题。其中最常见的问题就是 API 请求返回错误码。本文将介绍 RESTful API 常见的错误码、原因及排查技巧,并提供示例代码供读者参考。
1. 400 Bad Request
原因
客户端发送的请求有错误,如缺少必填参数、参数格式不正确等。
排查技巧
检查客户端请求的参数是否完整、格式是否正确。
// www.javascriptcn.com code example
$.ajax({
url: '/api/user',
method: 'POST',
data: {
name: 'John', // 缺少必填参数 `age`
},
success: function(result) {
console.log(result);
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr.status); // 400
console.log(xhr.responseText); // 错误信息
}
});2. 401 Unauthorized
原因
客户端请求需要用户认证的资源,但没有提供有效凭据。
排查技巧
检查客户端是否提供了有效的认证凭证,如用户名和密码或者 OAuth2.0 Token。
// www.javascriptcn.com code example
$.ajax({
url: '/api/user/1',
method: 'GET',
headers: {
'Authorization': 'Bearer invalid_token', // 无效的 Token
},
success: function(result) {
console.log(result);
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr.status); // 401
console.log(xhr.responseText); // 错误信息
}
});3. 403 Forbidden
原因
客户端没有访问权限,如访问需要管理员权限的资源。
排查技巧
检查客户端所使用的凭证是否具有访问权限或者 API 的权限控制是否正确配置。
// www.javascriptcn.com code example
$.ajax({
url: '/api/user/1',
method: 'DELETE',
headers: {
'Authorization': 'Bearer valid_token',
},
success: function(result) {
console.log(result);
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr.status); // 403
console.log(xhr.responseText); // 错误信息
}
});4. 404 Not Found
原因
请求的资源不存在。
排查技巧
检查请求的资源路径是否正确。
// www.javascriptcn.com code example
$.ajax({
url: '/api/user/999', // 不存在的用户 ID
method: 'GET',
success: function(result) {
console.log(result);
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr.status); // 404
console.log(xhr.responseText); // 错误信息
}
});5. 500 Internal Server Error
原因
服务器发生了未知的错误,无法处理客户端请求。
排查技巧
联系后端开发人员排查问题。
// www.javascriptcn.com code example
$.ajax({
url: '/api/user/1',
method: 'DELETE',
headers: {
'Authorization': 'Bearer valid_token',
},
success: function(result) {
console.log(result);
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr.status); // 500
console.log(xhr.responseText); // 错误信息
}
});结语
本文介绍了 RESTful API 常见的错误码、原因及排查技巧,并提供了相应的示例代码。阅读本文可以帮助前端开发人员更快速、更准确地排查 API 请求错误。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67cfc856e46428fe9ebc1c2c