EXCEPTION:位于0的JSON中出现意外的标记W.

时间:2016-11-08 15:50:09

标签: angular

我正在尝试使用http get方法将句子“How is weather in Tallinn?”发送到后端。 发送包含空格和?符号的完整句子非常重要。

以下是代码:

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 个答案:

答案 0 :(得分:2)

这是因为返回一个简单的字符串(纯文本)作为响应。该文本不是有效的JSON。因此,当您尝试res.json()时,会调用JSON.parse(data)。尝试使用您提供的字符串进行操作,您将收到相同的错误。

Unexpected token W in JSON at position 0

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