2016-11-08 55 views
0

我试图用http get方法将句子“How is weather in Tallinn?”发送到后端。 用空格和?符号发送完整句子很重要。EXCEPTION:在位置0的JSON中出现意外的令牌W

下面是代码:

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

,但我认为,在线路res.json()它与错误抱怨:

Unexpected token W in JSON at position 0 

的响应串Weather in Tallinn? Tempeture:-2 and in gneral:Rainy 因此,我认为,它与Weather并开始那么它无法处理它。

那么我该如何解决它?

+1

您正试图将字符串转换为角度边的JSON对象。 JSON对象始终是键:值对。改变对象的响应;例如:{“message”:“you message”},然后从角度方面提取属性**消息**以获取值。 – Lipu

回答

1

这是因为一个简单的字符串(纯文本)作为响应返回。该文本不是有效的JSON。所以当你试图做res.json()时,它会调用JSON.parse(data)。试着用你提供的字符串来做,你会得到同样的错误。

Unexpected token W in JSON at position 0 

如果只是纯文本,那么你可以做res.text()获得原始字符串。

相关问题