语法错误:JSON 中的意外标记 C 位于位置 0

Dea*_*Dea 7 json http observable typescript angular

我的应用程序中有这部分代码

addComment (body: Object): Observable<Comment[]> {
    //let bodyString = JSON.stringify(body); // Stringify payload
    let bodyString = JSON.parse(JSON.stringify(body || null ))
    let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
    let options = new RequestOptions({ headers: headers }); // Create a request option

    return this.http.post(this.commentsUrl, bodyString, options) // ...using post request
                        .map((res:Response) => res.json()) // ...and calling .json() on the response to return data
                        .catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}   
Run Code Online (Sandbox Code Playgroud)

当我尝试在我的应用程序中添加评论时,它会引发如下错误:

POST http://localhost:4200/assets/comments.json 404 (Not Found)   
SyntaxError: Unexpected token C in JSON at position 0
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我吗?

完全语法错误堆栈:

SyntaxError: Unexpected token C in JSON at position 0
    at Object.parse (<anonymous>)
    at Response.Body.json (body.js:24)
    at CatchSubscriber.selector (comment.service.ts:41)
    at CatchSubscriber.error (catch.js:104)
    at MapSubscriber.Subscriber._error (Subscriber.js:128)
    at MapSubscriber.Subscriber.error (Subscriber.js:102)
    at XMLHttpRequest.onLoad (xhr_backend.js:82)
    at ZoneDelegate.webpackJsonp.1301.ZoneDelegate.invokeTask (zone.js:363)
    at Object.onInvokeTask (ng_zone.js:264)
    at ZoneDelegate.webpackJsonp.1301.ZoneDelegate.invokeTask (zone.js:362)
    at Zone.webpackJsonp.1301.Zone.runTask (zone.js:166)
    at XMLHttpRequest.ZoneTask.invoke (zone.js:416)
Run Code Online (Sandbox Code Playgroud)

Udl*_*ati 7

我正面临着这个问题。

只是改变:

error.json()
Run Code Online (Sandbox Code Playgroud)

JSON.parse(JSON.stringify(error))
Run Code Online (Sandbox Code Playgroud)


小智 0

当我尝试在请求中发送空正文时,我遇到了类似的问题。您能否确认发送的正文不是未定义的?

您可以尝试在帖子周围添加一个条件,以在发送之前检查正文是否包含某些内容。