简体   繁体   中英

Angular2 Http.Delete Body is null

I followed the Angular2 tutorial but the Http.delete always throws an exception :
TypeError: this._body is null
Original code of hero.service.ts

public deleteHero(hero: Hero) {

    const headers = new Headers({
        'Content-Type': 'application/json'
    });

    return this._http
        .delete(this._heroesUrl + "/" + hero.Id, { headers: headers })
        .toPromise()
        .catch(this.handleError);
}

Actually, while the accepted answer is an effective work-around, the correct solution is to remove the Content-Type header. DELETE requests shouldn't have a body (empty or otherwise), and so neither should they have a Content-Type header. Same goes for GET requests. The error is thrown as a result of having a Content-Type header and no body (which is an illogical combination).

Turns out the one little thing I was missing was the following:

.delete(this._heroesUrl + "/" + hero.Id, { headers: headers, body: "" })

after headers: headers you can also set a body. Now since its a delete request there normally is no body. But if body is null angular will throw an exception ...

EDIT
This is a workaround but the actual answer is from @simon

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM