HttpClient导致错误

时间:2018-07-01 04:54:26

标签: angular

我正在使用Angular 4,并且想开始使用HttpClient。但是我收到JSON解析错误,经过大量搜索后,我仍无法修复它。

旧方法

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { _throw } from 'rxjs/observable/throw';
import { AppConfig } from '../config/app.config';
import { AuthenticateService } from '../security/shared/authenticate.service';
import { IFlower } from './flower.model';

addFlower(Flower: IFlower): Observable<any> {
    this._auth.checkToken();
    const headers = new Headers();
    this.createAuthorizationHeader(headers, this._auth.token);
    headers.append('Content-Type', 'application/json');
    this.options = new RequestOptions({ headers: headers });
    return this._http.post(this.apiUrl + 'flower/insert', JSON.stringify(Flower),
        this.options).map((res: Response) => <any>res).catch(this.handleError);
}

转换为HttpClient

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { _throw } from 'rxjs/observable/throw';
import { AppConfig } from '../config/app.config';
import { AuthenticateService } from '../security/shared/authenticate.service';
import { IFlower } from './flower.model';

    addFlower(Flower: IFlower): Observable<any> {
        this._auth.checkToken();
        const httpOptions = {
            headers: new HttpHeaders({
                'Authorization': 'Bearer ' + this._auth.token,
                'Content-Type':  'application/json'
            })
        };

        return this._http.post<any[]>(this.apiUrl + 'flower/insert', JSON.stringify(Flower), httpOptions)
            .pipe(
                catchError(this.handleError)
            );
    }

转换为HttpClient时,出现以下错误消息

https://core.rasa.com/patterns.html?highlight=fallback%20policy#fallback-default-actions

后端控制器代码:

[HttpPost]
[Route("insert")]
public HttpResponseMessage AddFlower(Flower flower)
{
    try
    {
        _flowerervice.AddFlower(flower, token));
        return Request.CreateResponse(HttpStatusCode.Created);
        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Forbidden"));
    }
    catch (Exception exception)
    {
        throw ExceptionMessageUtility.HttpResponse(Request, exception);
    }
}

我一直在寻找SO和其他来源。 Console error帖子解释了HttpClient,但这仍然不能解决我的错误。非常感谢您的帮助。 谢谢

1 个答案:

答案 0 :(得分:2)

Angular的HttpClient中最近发生的重大变化意味着,用HTTP 200 OK响应反序列化JSON正文的内容为空,现在会触发此“在JSON数据的...处意外的数据结尾”错误,因为应该使用HTTP 204 No Content。看到这里:https://github.com/angular/angular/issues/20879

有3种可能的解决方法:

  1. 更改您的网络服务,以便它返回带有空正文的HTTP 204。
  2. 更改您的网络服务,使其返回带有非空正文的HTTP 200。
  3. 更改您的客户端代码,以便它将空响应作为字符串返回,而不是尝试将其反序列化为JSON(设置{ responseType: "text" })。