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

記錄web踩過(guò)的坑

情景:

Angular 前臺(tái)向Java springboot的后臺(tái)請(qǐng)求一組List<User>

JAVA UserController返回一組List<User> :

UserController.java

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

Angular前臺(tái)調(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)用接口的頁(yè)面報(bào)錯(cuò)

Uncaught SyntaxError: Unexpected token < in JSON at position 1

排查錯(cuò)誤

嘗試1: json返回值格式錯(cuò)誤

因?yàn)殄e(cuò)誤是Json.parse, 首先想到的是服務(wù)器返回的數(shù)據(jù)格式不對(duì)
嘗試解決辦法

ionic generate class User

//創(chuàng)建class

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

然后在使用userservice的頁(yè)面挺狰, 把原本的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后刃永,報(bào)錯(cuò)仍舊存在

嘗試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 會(huì)有unxpected < 了

那么怎么解決呢艘狭?

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

HttpClient會(huì)返回html的情況基本只有一個(gè), 那就是服務(wù)器無(wú)響應(yīng)

既然后臺(tái)又是可以調(diào)通的巢音, 那原因只有一個(gè)了遵倦, 一定是URL放錯(cuò)了

檢查一看, 傻了

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
            });
    }

嗯嗯官撼,面壁.....

然后再打包梧躺,報(bào)了新錯(cuò)誤,

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 {
...
}

成功

總結(jié)

開發(fā)中的基本掠哥, url跨域訪問,header秃诵,處理返回值需要更熟練续搀,這次栽在了json parse想當(dāng)然得認(rèn)為是json返回值不規(guī)范, 做了很多次改動(dòng)菠净, 而問題其實(shí)出在不太相干的細(xì)節(jié)上禁舷。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市毅往,隨后出現(xiàn)的幾起案子牵咙,更是在濱河造成了極大的恐慌,老刑警劉巖攀唯,帶你破解...
    沈念sama閱讀 222,627評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件洁桌,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡侯嘀,警方通過(guò)查閱死者的電腦和手機(jī)战坤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,180評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)残拐,“玉大人途茫,你說(shuō)我怎么就攤上這事∠常” “怎么了囊卜?”我有些...
    開封第一講書人閱讀 169,346評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)错沃。 經(jīng)常有香客問我栅组,道長(zhǎng),這世上最難降的妖魔是什么枢析? 我笑而不...
    開封第一講書人閱讀 60,097評(píng)論 1 300
  • 正文 為了忘掉前任玉掸,我火速辦了婚禮,結(jié)果婚禮上醒叁,老公的妹妹穿的比我還像新娘司浪。我一直安慰自己泊业,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,100評(píng)論 6 398
  • 文/花漫 我一把揭開白布啊易。 她就那樣靜靜地躺著吁伺,像睡著了一般。 火紅的嫁衣襯著肌膚如雪租谈。 梳的紋絲不亂的頭發(fā)上篮奄,一...
    開封第一講書人閱讀 52,696評(píng)論 1 312
  • 那天,我揣著相機(jī)與錄音割去,去河邊找鬼窟却。 笑死,一個(gè)胖子當(dāng)著我的面吹牛呻逆,可吹牛的內(nèi)容都是我干的夸赫。 我是一名探鬼主播,決...
    沈念sama閱讀 41,165評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼页慷,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼憔足!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起酒繁,我...
    開封第一講書人閱讀 40,108評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤滓彰,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后州袒,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體揭绑,經(jīng)...
    沈念sama閱讀 46,646評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,709評(píng)論 3 342
  • 正文 我和宋清朗相戀三年郎哭,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了他匪。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,861評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡夸研,死狀恐怖邦蜜,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情亥至,我是刑警寧澤悼沈,帶...
    沈念sama閱讀 36,527評(píng)論 5 351
  • 正文 年R本政府宣布黎烈,位于F島的核電站酝掩,受9級(jí)特大地震影響预侯,放射性物質(zhì)發(fā)生泄漏晶伦。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,196評(píng)論 3 336
  • 文/蒙蒙 一窟坐、第九天 我趴在偏房一處隱蔽的房頂上張望丁逝。 院中可真熱鬧椰于,春花似錦惊搏、人聲如沸贮乳。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,698評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)塘揣。三九已至包雀,卻和暖如春宿崭,著一層夾襖步出監(jiān)牢的瞬間亲铡,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,804評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工葡兑, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留奖蔓,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,287評(píng)論 3 379
  • 正文 我出身青樓讹堤,卻偏偏與公主長(zhǎng)得像吆鹤,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子洲守,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,860評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容