例外:位置 0 处的 JSON 中的意外标记 W

Jef*_*eff 1 angular

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

这是代码:

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());
  }
}
Run Code Online (Sandbox Code Playgroud)

但我认为res.json()它会抱怨错误:

Unexpected token W in JSON at position 0
Run Code Online (Sandbox Code Playgroud)

响应是字符串Weather in Tallinn? Tempeture:-2 and in gneral:Rainy 所以我认为,它以开头Weather然后无法处理它。

那么我该如何解决呢?

Pau*_*tha 5

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

Unexpected token W in JSON at position 0
Run Code Online (Sandbox Code Playgroud)

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