将POST请求从Object解析为JSON



我试图向服务器发出POST请求,但我遇到了Angular问题。服务器似乎收到了请求,但我仍然在控制台中看到一个错误,建议将主体从Object更改为JSON

error:SyntaxError:JSON中位于JSON位置0的意外令牌A。在XMLHttpRequest.onLoad处解析(((http://localhost:4200/vendor.js:69142:51)文本:";一个新用户用id=:23"保存了它;proto:对象headers:HttpHeaders{normalizedNames:Map(0(,lazyUpdate:null,lazyInit:ƒ}消息:";解析期间Http失败http://localhost:8191/api/user"名称:";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版本的解决方案,其中它有@Angular/http过去,对于旧版本的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 HttpClient中的响应类型默认为json。您可以在请求中将其设置为text

尝试以下

addUser(user: User){
let body = JSON.stringify(user);
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({
headers: headers,
responseType: 'text'     // <-- set response type as `text`
});
return this._httpService.post("https://localhost:8443/api/user", body, options);
}

更新:新版本

您可以直接在请求中传递选项

createNewUser(user: User): Observable<Object>{
return this.httpClient.post(`${this.createURL}`, user, { responseType: 'text' });
}

最新更新