Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EXCEPTION: Unexpected token W in JSON at position 0

Tags:

angular

I am trying to send the sentence "How is weather in Tallinn?" with http get method to the back end. It is important to send complete sentence with the spaces and the ? sign.

Here is the code:

import { Injectable } from '@angular/core';
import {Http} from '@angular/http';
import "rxjs/Rx";

@Injectable()
export class HttpService {

  constructor(private http:Http) { }
  getAnswer(par:string){
    const query=par;
    console.log("value is:"+par);
   return  this.http.get('http://localhost:8080/?question='+query).map((res)=>res.json());
  }
}

but I think in line res.json() it complains with the error:

Unexpected token W in JSON at position 0

The response is string Weather in Tallinn? Tempeture:-2 and in gneral:Rainy So i think, it starts with Weather and then it cannot handle it.

So how can i fix it?

like image 778
Jeff Avatar asked Sep 01 '25 22:09

Jeff


1 Answers

It's because a simple string (plain text) is returned as the response. The text is not a valid JSON. So when you try to do res.json(), it calls JSON.parse(data). Try and do it with the string you provided, and you will get the same error.

Unexpected token W in JSON at position 0

If it's just plain text, then you can just do res.text() to get a raw string.

like image 138
Paul Samsotha Avatar answered Sep 03 '25 22:09

Paul Samsotha