response.text()不包含我所期望的内容

问题描述 投票:0回答:3

我有一个模拟文件mockedfile.html,我将其重定向到本地。我的问题是,当我尝试从fetch响应中提取HTML时,结果看起来与模拟文件不完全相同。所以这就是我做的:

fetch('/some-url.html').then(response => {
  if (response.redirected) { // this will be true locally
    fetch(response.url) // which will then be /mockedfile.html
      .then(res => res && res.text())
      .then(text => text) // expect this text to be the same as the content inside mockedfile.html, but this is just partly the same
  } else {
    response && response.text().then(text => text);
  }
}
})

我错过了什么?有没有更合适的方法来解决这个问题?

html dom fetch
3个回答
1
投票

要获取fetch之外的值,您需要第一个.then()返回一些东西。

额外的.then()是不必要的,因为它只是创建了一个解决相同值的新承诺。

fetch('/some-url.html')
  .then(response => {
    if (response.redirected) {
      return fetch(response.url)
        .then(res => res.text());
    }
    return response.text();
  })
  .then(console.log)
  .catch(console.error)

0
投票

你必须添加)然后打开闭合支撑(

   fetch('/some-url.html').then(response => {
  if (response.redirected) { // this will be true locally
    fetch(response.url) // which will then be /mockedfile.html
      .then(res => res && res.text())
      .then(text => text) // expect this text to be the same as the content inside mockedfile.html, but this is just partly the same
  } else {
    response && response.text().then(text => text);
  }
});
})

-1
投票
fetch(url).then(result => result.text()).then(yourText => ...);
© www.soinside.com 2019 - 2024. All rights reserved.