angular - Angular HTTP 请求获取响应正文
问题描述
我目前正在尝试弄清楚如何获取响应正文。我可以在浏览器的网络控制台中将其视为字符串数组(这是我想要得到的),但使用我的代码只会返回一个对象:
this.http.request(req).subscribe(event => {
if (event.type === HttpEventType.UploadProgress) {
const percentDone = Math.round(100 * event.loaded / event.total);
console.log(`File is ${percentDone}% uploaded.`);
} else if (event instanceof HttpResponse) {
console.log('File is completely uploaded!');
console.log('resp: ' + event.body);
}
});
这是一个 POST 请求。
这是日志:
resp: [object Object]
解决方案
您需要使用 JSON.stringify 来查看实际内容
console.log('resp: ' + JSON.stringify(event.body));
如果要从响应中访问特定字段,请使用 JSON.parse 转换为 Object
let filename = (JSON.parse(event.body)).fileName;