【问题标题】:JSON Error on clientside when sending ResponseEntity from serverside after post request发布请求后从服务器端发送 ResponseEntity 时客户端出现 JSON 错误
【发布时间】:2018-07-03 11:23:34
【问题描述】:

我有一个 angular/spring boot 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 的原因。

【问题讨论】:

  • 当我查看 chrome 开发工具的响应部分时,我可以看到响应是纯 tekst 而不是 JSON。

标签: java spring spring-rest spring-web


【解决方案1】:

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

{
  "status": "user created successfully"
}

尝试返回您的完整 status 对象而不是 status.getInfo(),那么您的返回对象应该类似于:

{
   "info": "user created successfully"
}

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

并且必须将您的返回类型更改为RepsonseEntity&lt;Status&gt;

【讨论】:

    【解决方案2】:

    实际上是的,您使用的是ResponseEntity,但使用String 作为正文,因为您使用的是:

    .body(status.getInfo());
    

    您需要在正文中指定一个对象,您可以创建一个 POJO 来为您保存消息,包装 status.getInfo() 字符串,它将被读取为 JSON。

    消息 POJO 类:

    public class MessageObject {
        private String message;
        //Constructors, getter and setter
    }
    

    您的返回码是:

    return ResponseEntity.status(status.isSuccess() ?
                    HttpStatus.CREATED : HttpStatus.BAD_REQUEST).body(new MessageObject(status.getInfo()));
    

    【讨论】:

    • responseBody 已经包含在方便注释@RestController
    猜你喜欢
    • 2021-09-08
    • 2014-01-13
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多