我正在开发一个以 angular 6 作为前端和 spring boot 作为 REST 后端的项目。 (英语不是我的母语,所以我提前为语法道歉。)
一切都很好,直到我在某些方法中遇到错误。
我正在从我的前端服务发出一个 http.post 请求,并从 spring boot 中得到一个错误,说内容类型应用程序/文本是不允许的(这不会发生在其他 PostMapping 方法上,但无论如何)我设法使用此代码更改帖子标题:
persistGame(game: Game) {
const path = 'http://localhost:8080/games';
const headers = new Headers();
headers.set('Content-Type', 'application/json; charset=utf-8');
const options = new RequestOptions();
options.headers = headers;
console.log(game);
return this.http.post(path, Game, options);
}
然后,console.log 显示了正确的对象,但我的后端开始提示 ""timestamp":"2018-09-05T20:11:04.848+0000","status":400,"error":"Bad Request","message":"JSON parse error: Unrecognized token 'function': was expecting 'null', 'true', 'false' or NaN;嵌套的异常是 com.fasterxml.jackson.core.JsonParseException:无法识别的标记“函数”:在 [Source: (PushbackInputStream) 处期待“null”、“true”、“false”或 NaN\n;行:1,列:10]","path":"/games"}"
当我检查有效载荷时,我发现了这个
"function Game() {
}"
而不是我的对象....
我的后端方法是这样的:
@CrossOrigin()
@PostMapping(path = "/games")
public ResponseEntity<Object> createGame(@RequestBody Game game) {
ResponseEntity<Object> output;
String body;
Game gameInBD;
gameInBD = gameService.findByName(game);
if (gameInBD == null)
{
gameService.saveGame(game);
} else
{
/* updates gameInDB fields with game fields and persist gameInDB */
}
output= ResponseEntity.ok(game);
return output;
如何避免这种从对象到函数的转换?
最佳答案
您正在将类作为参数发送给帖子
应该是这样的 ‘return this.http.post(path, game, options);’
小写游戏
关于Http.post() 正在将负载从对象更改为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52192863/