我有一个模拟文件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);
}
}
})
我错过了什么?有没有更合适的方法来解决这个问题?
要获取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)
你必须添加)然后打开闭合支撑(
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);
}
});
})
fetch(url).then(result => result.text()).then(yourText => ...);