<ANGULAR> Uncaught SyntaxError: Unexpected token < in JSON at position 1

記錄web踩過的坑

情景:

Angular 前臺向Java springboot的后臺請求一組List<User>

JAVA UserController返回一組List<User> :

UserController.java

@RestController
public class UserController {
..
    @GetMapping("/users")
    public List getUsers(){
        return userRepository.findAll();
    }
..
}

Angular前臺調(diào)用接口

user.service.ts

    public findAll(): Observable<User[]> {
        return this.httpclient.get<User[]>('http://localhost:8080/users', {headers : headers
            });
    }

使用service

users: Array[] = [];
..
..
  ngOnInit() {
      this.userService.findAll().subscribe(
          data => {
              console.log('type of response ' + JSON.stringify(data));
              this.users = data;
              // tslint:disable-next-line:no-shadowed-variable
          },   (error: any) => {
              console.log('error', error);
          }
      );
      console.log('user list content: ' + this.users);
  }

瀏覽器中, 可以獲得json返回值:

[{"id":3,"lastname":"Liu","firstname":"Jerry","email":"karen77777","password":null},{"id":4,"lastname":"Liu","firstname":"Jerry","email":"karen77777","password":null},{"id":5,"lastname":"Liu","firstname":"Jerry","email":"karen77777","password":null},{"id":6,"lastname":"Liu","firstname":"Jerry","email":"karen77777","password":null},{"id":7,"lastname":"Liu","firstname":"Jerry","email":"karen77777","password":"123333"},{"id":8,"lastname":"Liu","firstname":"Jerry","email":"karen77777","password":"123333"},{"id":9,"lastname":"Liu","firstname":"Jerry","email":"karen77777","password":"123333"},{"id":10,"lastname":"Liu","firstname":"Jerry","email":"karen77777","password":"123333"},{"id":11,"lastname":"Liu","firstname":"Jerry","email":"karen77777","password":"123333"},{"id":12,"lastname":"Liu","firstname":"Jerry","email":"karen77777","password":"123333"},{"id":13,"lastname":"Liu","firstname":"Jerry","email":"karen77777","password":"123333"},{"id":14,"lastname":"Liu","firstname":"Jerry","email":"karen77777","password":"123333"},{"id":15,"lastname":"Liu","firstname":"Jerry","email":"karen77777","password":"123333"},{"id":16,"lastname":"Liu","firstname":"Jerry","email":"karen77777","password":"123333"},]

然后打包app后, 發(fā)現(xiàn)調(diào)用接口的頁面報錯

Uncaught SyntaxError: Unexpected token < in JSON at position 1

排查錯誤

嘗試1: json返回值格式錯誤

因為錯誤是Json.parse, 首先想到的是服務器返回的數(shù)據(jù)格式不對
嘗試解決辦法

ionic generate class User

//創(chuàng)建class

export class User {
    id: number;
    lastname: string;
    firstname: string;
    password: string;
    email: string;
}

然后在使用userservice的頁面, 把原本的Array換成User[]

users: User[] = [];
..
..
  ngOnInit() {
      this.userService.findAll().subscribe(
          data => {
              console.log('type of response ' + JSON.stringify(data));
              this.users = data;
              // tslint:disable-next-line:no-shadowed-variable
          },   (error: any) => {
              console.log('error', error);
          }
      );
      console.log('user list content: ' + this.users);
  }

deploy生成安卓app后,報錯仍舊存在

嘗試2

檢查打包以后的瀏覽器response,
發(fā)現(xiàn)調(diào)用接口返回的竟然是ionic根目錄上的index.html文件?!

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>HoStream</title>

  <base href="/"/>

  <meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0">
  <meta name="description" content="HoStream live streaming LHS">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">

  <link rel="icon" type="image/png" href="assets/icon/favicon.png">

  <!-- add to homescreen for ios -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">

  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4F24AC">
</head>
<body>
  <app-root></app-root>
  <noscript>Please enable JavaScript to continue using this application.</noscript>
</body>
</html>

這樣,是可以解釋通為什么json parse 會有unxpected < 了

那么怎么解決呢?

既然手動調(diào)用接口是通的, 那么問題肯定出在前端上

HttpClient會返回html的情況基本只有一個, 那就是服務器無響應

既然后臺又是可以調(diào)通的, 那原因只有一個了, 一定是URL放錯了

檢查一看, 傻了

user.service.ts

    public findAll(): Observable<User[]> {
        return this.httpclient.get<User[]>('http://localhost:8080/users', {headers : headers
            });
    }

改成

user.service.ts

    public findAll(): Observable<User[]> {
        return this.httpclient.get<User[]>('http://192.168.0.104:8080/users', {headers : headers
            });
    }

嗯嗯,面壁.....

然后再打包,報了新錯誤,

XMLHttpRequest cannot load https://api.example.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

跨域訪問問題,在controller加上注釋

@RestController
@CrossOrigin
Public class UserController {
...
}

成功

總結

開發(fā)中的基本, url跨域訪問,header,處理返回值需要更熟練,這次栽在了json parse想當然得認為是json返回值不規(guī)范, 做了很多次改動, 而問題其實出在不太相干的細節(jié)上。

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容