首页 > 解决方案 > 以 html 格式获取帖子响应,但也获取状态

问题描述

我有一个对 API 的 fetch 调用。我需要两者status和 HTML 响应。

fetch('api/post/email', {
  method: 'POST',
  body: JSON.stringify(data)
}).then((response) => {
  console.log(response.text());
  console.log(response.body);

  if (response.status == 200) {
    console.log(response.status);
  } else {
    console.log(response.status);
  }
});

我从上面得到这个结果:

Promise {<pending>}
ReadableStream {locked: true}
404

最后一个status很好,但是...

使用 fetch 从 API 获取正文或 HTML 结果的最简单方法是什么?

标签: javascripttextfetchstatus

解决方案


fetch('api/post/email', {
  method: 'POST',
  body: JSON.stringify(data)
}).then((response) => {
  response.text().then(re => {
   console.log(re);
  });
  console.log(response.body);

  if (response.status == 200) {
    console.log(response.status);
  } else {
    console.log(response.status);
  }
});

Response.text() 返回一个承诺,因此您必须像处理它一样处理它。(传入回调)之后,您可以在回调中记录它。


推荐阅读