Spring ResponseEntity & AJAX error function:无法访问响应正文内容
Spring ResponseEntity & AJAX error function: can't access response body content
服务器端:Spring Framework
我有一个 Spring 控制器,它有一个返回类型 ResponseEntity<String>
的方法。
对于完全好的请求,我返回以下内容:
return new ResponseEntity<>(OK_MESSAGE, new HttpHeaders(), HttpStatus.OK);
但是如果在执行或异常捕获过程中有任何问题,我会返回:
return new ResponseEntity<>(ERROR_MESSAGE, new HttpHeaders(), HttpStatus.BAD_REQUEST);
其中ERROR_MESSAGE
包含捕获的每种异常类型的自定义字符串。
客户端:AJAX 调用
当调用该 POST 方法并返回 HttpStatus.OK时,AJAX
success: function (data, message, xhr)
被调用,我可以通过访问data
轻松访问字符串OK_MESSAGE
。
问题来了,POST 方法返回HttpStatus.BAD_REQUEST,AJAX
error: function (xhr, status, errMsg)
被调用,但我无法访问服务器发送的字符串ERROR_MESSAGE
,我需要向用户显示该字符串。
有什么建议吗?
在控制器上,我按以下方式返回响应实体:
return new ResponseEntity<>("Enter the full url", new HttpHeaders(), HttpStatus.BAD_REQUEST);
在JS中,我将通过以下方式检查响应错误字符串:
$.ajax({
url: 'http://localhost:8080/link',
data: 'url=/www.stackoverflow.om',
type: 'GET',
contentType: 'application/json; charset=utf-8',
success: function (data, textStatus, xhr) {
alert(xhr.status);
},
error: function (data, textStatus, xhr) {
alert(data.responseText);
}
})
相关文章:
- 存储$http如何从$http函数(Angularjs)外部获取可访问变量中的响应
- 访问令牌和响应数据
- 飞行前响应中的访问控制允许标头不允许Angularjs请求标头字段访问控制允许标题
- 响应式图片库,每个图片都可以通过锚链接访问
- 我如何设置HTTP头“;访问控制允许起源”;用于来自thttpd web服务器的HTTP响应
- 无法访问响应 JSON 对象
- 使用Backbone.js访问JSON响应的部分
- jQuery post,访问responseType或回调中的响应
- 从Web服务访问JSON响应
- 如何访问您没有访问的HTTP响应的标头't使用javascript通过AJAX发送
- 如何访问 iframe.contentDocument 以在跨源请求后获得响应
- 有没有任何方法可以从javascript进行跨域请求,并访问它可能生成的错误响应类型(401404等)
- 可以't从回调函数内部访问响应
- jQuery从PHP函数访问Ajax响应
- ReactJs-访问JSON响应中的嵌套数组
- 如何访问此json响应的数据
- Spring ResponseEntity & AJAX error function:无法访问响应正文内容
- 在Google可视化API中访问响应状态
- 如何在失败时从Angular HTTP拦截器访问响应体
- Node.js http服务器,功能可以't访问响应对象