Angular SyntaxError JSON.parse:意外字符

时间:2018-03-14 14:23:16

标签: angular angular-http

我正在使用此方法向特定网址发送http获取请求,响应为字符串(base64图像):

  public getSingleImage(imgId): Promise<any> {
    return new Promise((resolve, reject) => {
      const url = `${CONST.DOCUMENT_SINGLE_IMAGE}/${imgId}` + '/base64';
      this.http.get(url)
        .toPromise()
        .then((res: any) => {
          // value = res;
          resolve(res);
        }).catch((error) => {
          console.log(error);
        });
    });
  }

由于某些原因我收到错误JSON.parse: unexpected character at line 1 column 1 of the JSON data

以下是响应标题:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:4200
api-supported-versions: 1.0
Content-Type: text/plain; charset=utf-8
Date: Wed, 14 Mar 2018 14:01:07 GMT
Server: Kestrel
Transfer-Encoding: chunked
Vary: Origin

1 个答案:

答案 0 :(得分:2)

new angular's HTTP module现在默认为服务器的JSON响应。如果要更改它,则需要添加适当的HTTP标头。 尝试添加此标题:

{'responseType':'image/*'}

因此,您的获取请求应如下所示:

 this.http.get(url,{
 'responseType':'image/*'
})