如何访问获取响应的有效负载



我正在向Google脚本发送一个获取请求,并想知道如何获取响应的有效负载。

客户端代码:

fetch(url, {
method: 'POST',
body: JSON.stringify({ type: 'proposal' }),
headers: {
'Content-Type': 'text/plain;charset=utf-8',
}
}).then( (response) => {
console.log("success:", response);
}).catch(err => {
console.log("Error:" + err);
});

在服务器端(GAS(,我有这个:

function doPost(e) { 
return ContentService.createTextOutput('It works!'); // Please add this.
}

代码成功地发送了获取请求,通过Firefox开发工具查看Payload,我得到了预期的响应("It Works!"(。

然而,在我的日志中,我得到了响应对象。如何访问实际负载(脚本返回的ContentService TextOutput(。

看看MDN上的"使用Fetch"文档:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

来自fetch的响应是一个响应对象,它包括许多方法,您可以调用这些方法来获得解析的响应。它们中的每一个都返回一个promise,您需要根据响应中的数据类型调用正确的promise。

例如:

fetch('/url', {
method: 'POST'
...
}).then(res => res.text())
.then(text => {
...here is the text response
})

或者如果您的响应是JSON:

fetch('/url', {
method: 'POST',
...
}).then(res => res.json())
.then(json => {
...here is the JSON response
})

我想您正在寻找response.text()

fetch(...).then(response => response.text()).then(text => console.log(text));

我精心制作了这个简单的函数,它是不可用的,因为它返回了一个promise,因此它可以异步运行。

let makeRequest = function(URL){
return new Promise(function(callback){
fetch(URL).then(function(res){
res.text().then(callback);
});
});
}

wait一起使用:

let text = await makeRequest('https://stackoverflow.com');

老式电话:

makeRequest('https://stackoverflow.com').then(function(text){
// Do stuff with text
});

最新更新