如何获取并解析Google Chat webhook返回的响应数据为Message类型
你直接打印的是node-fetch返回的原始Response对象,还没有对响应体做JSON解析,因此看不到文档中定义的Message类型数据。按照如下方式修改代码即可:
const fetch = require('node-fetch'); const webhookURL = '<INCOMING-WEBHOOK-URL>'; const data = JSON.stringify({ text: 'Hello from a Node script!', }); fetch(webhookURL, { method: 'POST', headers: { 'Content-Type': 'application/json; charset=UTF-8', }, body: data, }) .then(response => { // 先判断请求是否正常返回 if (!response.ok) { throw new Error(`请求异常,状态码:${response.status}`); } // 解析响应体为JSON格式,即可拿到官方定义的Message类型数据 return response.json(); }) .then(messageResult => { // 此处打印的就是你需要的Message结果 console.log(messageResult); }) .catch(error => { console.error('调用接口出错:', error); });
如果更习惯async/await的写法,也可以改成如下形式:
const fetch = require('node-fetch'); async function sendWebhook() { const webhookURL = '<INCOMING-WEBHOOK-URL>'; const data = JSON.stringify({ text: 'Hello from a Node script!', }); try { const response = await fetch(webhookURL, { method: 'POST', headers: { 'Content-Type': 'application/json; charset=UTF-8', }, body: data, }); if (!response.ok) { throw new Error(`请求异常,状态码:${response.status}`); } const messageResult = await response.json(); console.log(messageResult); } catch (error) { console.error('调用接口出错:', error); } } sendWebhook();
补充说明:
- 你在返回结果里看到的Gunzip压缩流,
node-fetch会自动处理解压,不需要你手动操作,直接调用response.json()即可正确解析数据。 - 如果遇到JSON解析失败的情况,可以临时将
response.json()替换为response.text(),打印原始响应内容排查格式问题。
内容的提问来源于stack exchange,提问作者Jose Arrillaga
相关产品推荐
相关产品推荐

