gpt4 book ai didi

javascript - Angular 5 不显示服务器的响应值

转载 作者:行者123 更新时间:2023-12-01 02:00:30 25 4
gpt4 key购买 nike

看来我的客户端没有捕获来自服务器的响应值并显示它。

这是我的组件代码:

export class MyComponent implements OnInit {

data: string;

constructor(private myService: MyService) {}

ngOnInit() {}

testCall() {
this.myService.getData().subscribe(data => this.data = data);
console.log("Data: " + this.data);
}
}

服务代码:

@Injectable()
export class MyService {

private url = 'http://localhost:5000/myproj/api/test';

constructor(private http: HttpClient) { }

// Get data from the server
getData(): Observable<string> {
console.log("in getData() method");
return this.http.get<string>(this.url)
.pipe(
catchError(this.handleError) // then handle the error
);
}

private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return new ErrorObservable('Something went wrong; please try again later.');
};
}

请求发送到服务器,服务器以响应正文中的数据和状态代码 200 进行响应,您可以在 Internet Explorer 的开发人员工具中看到该状态代码:

enter image description here

但由于某种原因,当我调用服务方法getData()时,Angular客户端代码调用我定义的catchError()方法,并打印:

Backend returned code 200, body was: [object Object]
ERROR Something went wrong; please try again later.

为什么服务器返回状态 200(正常),但 Angular 客户端却调用 catchError() 方法?

编辑:

这是我的服务器端 API 代码:

@RequestMapping(value = "/test", method = RequestMethod.GET, produces = "text/plain")
public String testApi(HttpServletRequest request) {

System.out.println("in /test");

String response = "my response";

return response;
}

最佳答案

响应正文不是正确的 JSON 格式,因此反序列化时会产生“无效字符”错误。该服务需要正确格式的 JSON。

使用“application/json”更新您的 API 以返回有效的 JSON 对象并返回一个对象,如以下帖子所示:Spring MVC - How to return simple String as JSON in Rest Controller

关于javascript - Angular 5 不显示服务器的响应值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50629118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com