promise - 从 Fetch API 返回正文文本
问题描述
我想返回我通过 fetch 发送的 POST 返回的响应正文文本。
var r = '';
var res = fetch(this.commentsUrl, {
method: 'post',
body: JSON.stringify(comment),
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
return response.text().then(function (text) {
r = text;
})
});
r 或 res 都没有返回正文。他们都在返回 Promise。我如何只返回正文?
解决方案
我能够使用await
.
const response = await fetch(this.commentsUrl, {
method: 'post',
body: JSON.stringify(comment),
headers: {
'Content-Type': 'application/json'
}
});
const text = await response.text();