【问题标题】:Http failure during parsing for http解析 http 期间的 Http 失败
【发布时间】:2019-12-17 02:10:06
【问题描述】:

我正在使用带有 REST api 的 Angular 连接到后端。我正在传递用户名和密码以访问资源,servletFilter 看起来很好,问题出在浏览器发送响应时。生成此错误。我已经阅读了很多这样的问题,但找不到能解决我问题的问题

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", 
url: "http://localhost:8080/front", ok: false, …}
error:
error: SyntaxError: Unexpected token < in JSON at position 0 at 
JSON.parse (<anonymous>) at XMLHttpRequest.onLoad 
(http://localhost:4200/vendor.js:10132:51) at ZoneDelegate.invokeTask 
(http://localhost:4200/polyfills.js:3626:31) at Object.onInvokeTask 
text: "
__proto__: Object
headers: HttpHeaders
lazyInit: () => {…}
lazyUpdate: null
normalizedNames: Map(0) {}
 __proto__: Object
message: "Http failure during parsing for 
http://localhost:8080/front"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/front"
__  proto__: HttpResponseBase

这是登录服务

constructor (private http : HttpClient){}
sendCredential(username: string, password: string){
    let url = "http://localhost:8080/index";
    let params = 'username='+username+'&password='+password;
    let headers = new HttpHeaders(
    {
        'Content-Type': 'application/x-www-form-urlencoded'
        // 'Access-Control-Allow-Credentials' : true
    });
    return this.http.post(url,params,{headers: headers, withCredentials : true}).pipe(res => {
    return res;
    });

这里是调用登录服务方法的登录组件方法

onSubmit() {
this.loginService.sendCredential(this.username, this.password).subscribe(
  res => {
    this.loggedIn=true;
    localStorage.setItem('PortalAdminHasLoggedIn', 'true');
    location.reload();
  },
  err => console.log(err)
);
 }

感谢您的帮助

【问题讨论】:

  • 首先您在开发者工具下的网络选项卡中检查响应类型。如果不是 json,则准备 json 格式的服务器端数据。

标签: angular rest spring-boot servlets


【解决方案1】:

当来自 REST 服务的响应返回以尖括号开头的 html 页面时会出现此错误,这就是出现此错误的原因

Unexpected token < in JSON at position 0 at 

JSON.parse()

为了不引发错误的响应,您必须将响应设置为来自服务端的 JSON 响应,该响应以 json 样式的花括号 {

您可以通过打开开发人员工具并在网络选项卡下查看响应。然后发出登录请求,然后单击该记录并查看它在响应选项卡右侧显示 bin 的详细信息,您将找到一个 html 页面

【讨论】:

  • 当我使用 x-www-form-urlencoded 时我应该怎么做
  • 它不是来自您这边,而是来自后端,服务将返回 Json 而不是 Html 页面。请检查服务后端并使其返回 json
【解决方案2】:

这可能是因为来自服务器的响应没有返回有效的 JSON。 检查您的网络选项卡并查看传入的服务器响应。

【讨论】:

  • 这正是问题所在,但是如何在服务器中将html转换为json
  • 这取决于您在服务器端使用的语言。
  • 我正在使用 java Spring-boot
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-13
  • 1970-01-01
  • 2020-06-03
  • 2019-11-13
  • 2023-02-21
相关资源
最近更新 更多