java - 发布请求后从服务器端发送 ResponseEntity 时客户端出现 JSON 错误
问题描述
我有一个角度/弹簧启动 webapp。当我发送创建用户后请求时,角度客户端应用程序无法读取我在操作后发回的响应实体的正文。错误是:
{error: SyntaxError: Unexpected token U in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text: "User successfully created."}
我知道这是因为正文内容不是 JSON 格式。但是,即使我将produces = "application/json"
作为属性添加到@PostMapping
注释中,错误仍然存在。
继承人的代码:
@RestController
@RequestMapping("api/user")
public class UserController {
private final Log logger = LogFactory.getLog(this.getClass());
@Autowired
UserService userService;
@Autowired
UserDao userDao;
@PostMapping(path = "/create", produces = "application/json")
private ResponseEntity<String> createNewUser(@RequestBody UserCreateDTO newUser) {
logger.info("name is: " + newUser.getUserName());
Status status = userService.createUser(newUser);
return ResponseEntity.status(status.isSuccess() ?
HttpStatus.CREATED : HttpStatus.BAD_REQUEST).body(status.getInfo());
}
我应该怎么做才能解决这个问题?我认为这与 ResponseEntity 的使用有关。我可以只发送我已经返回的状态 DTO 对象,但是我希望能够操作也发送回来的 httpStatus 代码,所以这就是我想使用 ResponseEntity 的原因。
解决方案
看起来您正在返回字符串文字而不是 json 对象。转换为 json 时的返回对象应该是这样的
{
"status": "user created successfully"
}
尝试返回你的完整status
对象而不是status.getInfo()
你的返回对象应该看起来像:
{
"info": "user created successfully"
}
你可以status.info
在你的javascript中调用来引用返回
并且必须将您的返回类型更改为RepsonseEntity<Status>
推荐阅读
- javascript - Rails 6:渲染部分后执行 JS 函数
- lua - keycreator:21: 尝试在本地 'iLevel' 上执行算术运算(一个 nil 值)
- haskell - 如何从特定形式的数据类型中提取信息?
- flask - 带有 GeoAlchemy 列的 Flask 模型
- javascript - 以不可变的方式删除嵌套数组中的对象
- .net - UiPath Microsoft Graph 身份验证
- microsoft-graph-api - 如何通过 REST API 在 Teams 频道内更新(编辑)Microsoft Teams 消息(线程或回复)
- ruby-on-rails - 为什么我不能创建新类的实例?
- javascript - 如何在vue js中刷新/离开页面之前加载对话框?
- reactjs - 嵌套数组中的 setState