问题描述
我正在尝试通过ID删除一个简单的学生对象。它工作正常。但它不会显示成功消息,而是将成功消息作为错误消息返回。
@DeleteMapping("/student/{$id}")
public String deleteStudent(@PathVariable int $id){
return student_service.deleteStudent($id);
}
服务代码:
public String deleteStudent(int $id){
student_repository.deleteById($id);
return "student deleted,id: "+$id;
}
public deleteStudentById($id: number): Observable<string>{
return this.http.delete<string>(this.url + `student/${$id}`);
}
主要类别代码:
deleteStudentById($id: number): void{
this.httpService.deleteStudentById($id)
.subscribe(
(res => console.log(res)),(error => console.log(error))
);
}
控制台错误:
HttpErrorResponse {headers: HttpHeaders,status: 200,statusText: "OK",url: "http://localhost:8080/student/3",ok: false, …}
SyntaxError: Unexpected token s in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:124662:51) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:495:35) at Object.onInvokeTask (http://localhost:4200/vendor.js:82248:33) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:494:40) at Zone.runTask (http://localhost:4200/polyfills.js:263:51) at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:576:38) at invokeTask (http://localhost:4200/polyfills.js:1717:18) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:1754:25)
message: "Unexpected token s in JSON at position 0"
stack: "SyntaxError: Unexpected token s in JSON at position 0↵ at JSON.parse (<anonymous>)↵ at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:124662:51)↵ at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:495:35)↵ at Object.onInvokeTask (http://localhost:4200/vendor.js:82248:33)↵ at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:494:40)↵ at Zone.runTask (http://localhost:4200/polyfills.js:263:51)↵ at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:576:38)↵ at invokeTask (http://localhost:4200/polyfills.js:1717:18)↵ at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:1754:25)"
__proto__: Error
constructor: ƒ SyntaxError()
message: ""
name: "SyntaxError"
__proto__: Object
text: "student deleted,id: 3"
__proto__: Object
headers: HttpHeaders
lazyInit: () => {…}
lazyUpdate: null
normalizednames: Map(0) {}
__proto__: Object
message: "Http failure during parsing for http://localhost:8080/student/3"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/student/3"
__proto__: HttpResponseBase
[1]
对不起,我忘记了声明部分。这里的http是HttpClient的类型。
private http: HttpClient;
private url: string = 'localhost:8080';
private httpService: StudentService;
在此处控制台屏幕截图[1]:https://i.stack.imgur.com/dW1Ql.png
解决方法
Angular HTTP客户端需要一个JSON对象作为响应内容。但是,您的端点提供纯文本。请使用相应的响应类型。
return this.http.delete<string>(this.url + `student/${$id}`,{ responseType: 'text' });