2017-05-28 168 views
0

您好:我讓我的腳溼與平均堆棧。所以我使用Angular連接到api.js文件,該文件與我的mongodb數據庫連接。不過,我收到以下錯誤:這是在錯誤中引用如何解決:意外標記<在JSON在位置0

ERROR SyntaxError: Unexpected token < in JSON at position 0 
    at JSON.parse (<anonymous>) 
    at Response.Body.json (http.es5.js:800) 
    at MapSubscriber.project (post.service.ts:19) 
    at MapSubscriber._next (map.js:77) 
    at MapSubscriber.Subscriber.next (Subscriber.js:89) 
    at XMLHttpRequest.onLoad (http.es5.js:1229) 
    at ZoneDelegate.invokeTask (zone.js:424) 
    at Object.onInvokeTask (core.es5.js:4140) 
    at ZoneDelegate.invokeTask (zone.js:423) 
    at Zone.runTask (zone.js:191) 

post.service.ts文件如下:

import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 
import 'rxjs/add/operator/map'; 

@Injectable() 
export class PostService { 

    result: any; 

    constructor(private _http: Http) { } 

    getPosts() { 
    return this._http.get("/api/posts") 
     .map(result => this.result = result.json()); 
    } 

    getPost(id) { 
    return this._http.get("/api/details" + id) 
     .map(result => this.result = result.json()); 
    } 

} 

以下是我的api.js文件。即使控制檯也不會登錄該帖子。

router.get('/details/:id', function(req, res) { 
    console.log('Requesting post'); 
    post.findById(req.params.id) 
     .exec(function(err, post) { 
      if (err) { 
       console.log('Error getting the post'); 
      } else { 
       res.json(post); 
       console.log(post); 
      } 
     }); 
}); 

我不知道我在哪裏錯了。我會很感激任何指導。

+0

你在哪裏得到這個錯誤?在Chrome控制檯中輸入 – Aravind

+0

。然而,當我試圖拉出所有帖子時,我沒有得到那個錯誤;只有當我嘗試請求單個帖子時 – Nosail

+0

您期望返回JSON的內容實際上是返回HTML,因此將<<作爲第一個字符。這可能是託管該API的服務器上的標準錯誤頁面,可能是4xx或可能是5xx。所以服務器上的代碼可能會失敗,或者路線錯誤。您將能夠通過檢查瀏覽器開發工具中的網絡選項卡來查看返回結果。或添加'。做(響應=>的console.log(response.text()))''你.MAP()' –

回答

1

你的API缺少一些部分,假設你發送請求到not found文章或server error,然後你沒有發送任何或錯誤的HTML到客戶端。所以要儘量將消息發送到客戶端,如:

if (err) { 
    console.log('Error getting the post'); 
    res.status(500).json({error: err.message, errorCode: /*some number code*/ 1101}); 
} else { 
     /* logic for not found maybe */ 
     // and logic for result 
     res.json(post); 
     console.log(post); 
} 

和URL應該是:get("/api/details/" + id)

+0

是的..謝謝,我固定的網址..這是我要去哪裏錯了 – Nosail

+0

你可以更新您的API作爲我上面的例子,它可以防止未來的問題 –

相關問題