Angular:HttpErrorResponse:“解析期间的Http失败...” - 从服务器成功返回的String

问题描述 投票:1回答:3

Spring-boot RESTful服务器端;一种将返回字符串的测试方法:

@RequestMapping(value = "test", method = RequestMethod.GET)
    public ResponseEntity<String> test(HttpServletRequest req, HttpServletResponse resp) {
        try {
            return new ResponseEntity<String>("Test has worked, biatch!", HttpStatus.OK);
        } catch (Exception e) {
            System.err.println("## EXCEPTION: " + e.getMessage());
            return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }

来自Postman-一切正常,我从JSON中正确解析了String。

但是,当我从Angular客户端尝试相同时,我不断生成一个HttpErrorResponse对象。

  public url: string = "http://localhost:8080/theater/admin/test";
  constructor(private as: AdminService, private http: HttpClient) { }

  ngOnInit() {
  }

  getTest() {
    this.as.getTest()
      .subscribe(data => console.log(data), // this should happen on success
        error => console.log(error));  // this should happen on error
  }

很有趣,它包含从服务器返回的字符串,我可以在订阅功能上使用error.text访问它。控制台上的Error对象:

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/theater/admin/test", ok: false, …}
error
:
{error: SyntaxError: Unexpected token T in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text: "Test has worked, biatch!"}
headers
:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message
:
"Http failure during parsing for http://localhost:8080/theater/admin/test"
name
:
"HttpErrorResponse"
ok
:
false
status
:
200
statusText
:
"OK"
url
:
"http://localhost:8080/theater/admin/test"
__proto__
:
HttpResponseBase

这可能与解析从服务器返回的包含String的JSON对象有关。然而,返回对象,集合和其他任何东西 - 完全正常 - .subscribe()解析我从服务器正确获得的任何对象,或者如果服务器发生异常,返回的HttpStatus正确调用客户端的HttpErrorResponse。

那么,Strings错误解雇是怎么回事?无论如何,我总是得到一个HttpErrorResponse。我在这里做错了吗?

json string angular parsing string-parsing
3个回答
6
投票

测试工作,biatch!

这不是JSON。因此解析错误。

这可能与解析从服务器返回的包含String的JSON对象有关。然而,返回对象,集合和其他任何东西 - 完全正常 - .subscribe()

那么它适用于POJO因为它们是JSON编码的。在这里你有简单的String

要以字符串而不是对象来获取响应,请执行类似的操作

 http.get(url, {responseType: 'text'})

2
投票

尝试这样的事情 -

{ responseType: 'text' as 'json' }

在Angular 7中遇到与HttpClient相同的问题,使用上面的对象设置解决了。


0
投票

我通过使用JsonObject正确构建然后插入ResponseEntity的JSON字符串解决了这个问题:

@PostMapping(...)
public ResponseEntity handler(HttpServletRequest req, HttpServletResponse resp) {
  JsonObjectBuilder builder = Json.createObjectBuilder();
  builder.add("text", "Hello World!");
  JsonObject json = builder.build();

  return new ResponseEntity<>(json.toString(), HttpStatus.OK);
}

© www.soinside.com 2019 - 2024. All rights reserved.