SyntaxError: Unexpected token C in JSON at position 0
Asked Answered
P

7

7

I have this part of code in my application

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
}   

When I try to add a comment in my application it throws an error as below:

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

Someone can help me?

Fully SyntaxError stack:

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)
Promptbook answered 8/3, 2017 at 16:21 Comment(5)
Can we have a look at how you're calling addComment ?Westhead
Why do you stringify, then parse?Invaginate
Can you attach the SyntaxError stack, to indicate which code line throws the error? And when addComment is invoked, what is the value of this.model object?Consol
@Consol the value of this.model is [object Object].Promptbook
According to the stack, the SyntaxError origins from Response.Body.json (body.js:24) and CatchSubscriber.selector (comment.service.ts:41). Which one appears in your code? And which line does it indicate?Consol
S
8

I was facing the exactly issue.

Just change:

error.json()

to

JSON.parse(JSON.stringify(error))
Sculpturesque answered 29/3, 2017 at 13:13 Comment(1)
Working Like a Charm !! :)Imposture
S
3

You might have echoed something that starts with C like Connected You should echo only json response and not any String in general!

Supersaturated answered 13/7, 2020 at 16:40 Comment(0)
P
1

I was having similar issues. I found out that return type function from spring boot was not supported in Angular. The return type of the function was ResponseEntity<String>.

return ResponseEntity.ok().body(new String("Some Message"));

I changed it to ResponseEntity<ResponseMessage> and modified the return as

return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage("Some Message"));

And it worked. The ResponseMessage class contained

  public class ResponseMessage {
  private String message;

  public ResponseMessage(String message) {
    this.message = message;
  }

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

}

Thanks to Stackoverflow community. This is my first Answer.

Pledget answered 16/7, 2020 at 4:49 Comment(0)
C
0

I have had a similar issue when I attempt to send an empty body in the request. Can you confirm that the body being sent is not undefined?

You could try adding a condition around the post that checks if the body contains something before sending.

Codie answered 8/3, 2017 at 16:30 Comment(0)
M
0

I got similar error when my php file contained connection successfull message. When i removed all echo commands expect that of json_encode(),i got it working So Make sure that in your php file there is only echo of echo json_encode($data)

Mussorgsky answered 25/5, 2017 at 2:25 Comment(0)
G
0

can you try with this code

example

  addComment(user: ApiDashboard) {
   return this.http.post(this.commentsUrl,user).map(response => 
   response.json());
   }

you can try with

  addComment(user: Comment) {
   return this.http.post(this.commentsUrl,user).map(response => 
   response.json());
   }

here Comment is model file

for example

export class ApiDashboard {
id: string;
name: string;
price: number;
 }
  • this case appears when you have printed some values in service file in my case

service.ts

 private handleError(error: any): Promise<any> {
//console.error('An error occurred', error); 
return Promise.reject(error.message || error);
 }

i commented console.log() then it may works fine can you try solution.

Goral answered 8/8, 2017 at 9:55 Comment(0)
S
0

 if (text.startsWith("Connected successfully")) {
  // If it does, remove this part and parse the remaining JSON
 const jsonText = text.substring("Connected successfully".length);
const jsonData = JSON.parse(jsonText);
resolve(jsonData);

i was facing with the same error SyntaxError: Unexpected token C in JSON at position 0 so i removed the unwanted parts from the response and process only the JSON data.

Swirl answered 16/4 at 7:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.