首页 > 解决方案 > 发布请求后从服务器端发送 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 的原因。

标签: javaspringspring-restspring-web

解决方案


看起来您正在返回字符串文字而不是 json 对象。转换为 json 时的返回对象应该是这样的

{
  "status": "user created successfully"
}

尝试返回你的完整status对象而不是status.getInfo()你的返回对象应该看起来像:

{
   "info": "user created successfully"
}

你可以status.info在你的javascript中调用来引用返回

并且必须将您的返回类型更改为RepsonseEntity<Status>


推荐阅读