【发布时间】:2020-11-17 13:21:50
【问题描述】:
我尝试向服务器发出 POST 请求,但我遇到了 Angular 问题。 似乎服务器收到了请求,但我仍然在控制台中看到一个错误,建议将正文从 Object 更改为 JSON
错误:SyntaxError:JSON.parse 中位置 0 处的 JSON 中的意外令牌 A () 在 XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:69142:51) text: "一个新用户用 id = : 23 保存" 原型:对象 标头:HttpHeaders {normalizedNames:Map(0),lazyUpdate:null,lazyInit:ƒ} 消息:“解析 http://localhost:8191/api/user 期间的 Http 失败” 名称:“HttpErrorResponse”
例如,在我的 cod 中,我需要解决这个问题,因为我在提交时尝试导航到另一个页面。
createNewUser(user: User): Observable<Object>{
return this.httpClient.post(`${this.createURL}`,user);
}
saveNewUser(){
this.userService.createNewUser(this.user).subscribe( data =>{
console.log(data);
this.router.navigateByUrl('/list-user');
},
error => console.log(error));
}
针对具有 @angular/http 的旧 Angular 版本的解决方案 过去,对于旧版本的 Angular,比 10 还早,我知道我可以像下面那样做,但现在不是 RequestOptions 我无法导入它,因为它需要 @angular/http:
addUser(user: User){
let body = JSON.stringify(user);
//pass the content type which is aoolication/JSON cintent
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
//pass body and options
return this._httpService.post("https://localhost:8443/api/user", body, options);
}
您还有其他解决方案吗?
【问题讨论】:
标签: angular typescript