Response body is null, status is 200

2020-08-20 08:35发布

问题:

I'm using Angular's new HttpClient for requests. When I was using the old http, my component returned the body text just fine, but now the body text is null. I can't figure it out, the server is sending it, but i'm always receiving null as the body.

every other part of the response is normal, status 200 etc. Both the put and the delete expect a plain text success message. I have also tried using the .body method to get the body text, and that returns null as well.

service:

constructor(private http: HttpClient) {}

    sendAllow(country, allow) {
        if (allow === 1) {
            return this.http.put(`http://${this.address}/rest/geodrop/config/` +
                                 `${country}`, { observe: 'response' });
        } else {
            return this.http.delete(`http://${this.address}/rest/geodrop/config/` +
                                    `${country}`, { observe: 'response' });
        }
    }

component:

this.whiteListService.sendAllow(a, b)
            .subscribe(
                (response) => console.log(response),
                (error) => {
                    console.log(error);
                }
        );

回答1:

The problem is Angular is expecting a json response. change the response to type text like so:

return this.http.put(`http://${this.address}/rest/geodrop/config/` +
                     `${country}`, { responseType: 'text', observe: 'response' });