使用npm的got.post请求第三方接口返回未知内容,是否用法有误?
问题原因
got库的所有请求方法默认返回Promise异步对象,你没有等待异步请求执行完成就直接打印res变量,此时输出的是未完成状态的Promise实例,就是你截图中看到的内容,并非接口实际返回的响应数据。
解决方案
有两种常用写法获取实际响应内容:
1. async/await 写法(推荐)
将请求逻辑包裹在async标记的函数中,用await等待异步请求完成:
// 注意请求逻辑要放在async标记的函数内 const fetchData = async (index, size) => { try { const res = await got.post('https://c.jushuitan.com/api/open/query.aspx?ts=1632820982&partnerid=ywv5jGT8ge6Pvlq3FZSPol345asd&method=mall.item.query&token=181ee8952a88f5a57db52587472c3798&sign=e101d5a0662dc9723415a941d4f2d606', { json: { "modified_begin": "2021-09-06 00:00:00", "modified_end": "2021-09-07 00:00:00", "page_index": index, "page_size": size, "sku_ids": null } }) // 打印原始响应体 console.log(res.body) // 如果接口返回JSON格式,可以直接调用.json()方法获取解析后的对象 // const resJson = await got.post(/* 请求参数 */).json() // console.log(resJson) } catch (err) { // 捕获请求异常 console.error('请求出错:', err.response?.body || err.message) } }
2. Promise.then 写法
got.post('https://c.jushuitan.com/api/open/query.aspx?ts=1632820982&partnerid=ywv5jGT8ge6Pvlq3FZSPol345asd&method=mall.item.query&token=181ee8952a88f5a57db52587472c3798&sign=e101d5a0662dc9723415a941d4f2d606', { json: { "modified_begin": "2021-09-06 00:00:00", "modified_end": "2021-09-07 00:00:00", "page_index": index, "page_size": size, "sku_ids": null } }).then(res => { console.log(res.body) }).catch(err => { console.error('请求出错:', err.response?.body || err.message) })
额外排查方向
如果修改写法后仍返回异常内容,可依次排查以下问题:
- 请求参数中的
ts时间戳、sign签名是否有效,聚水潭开放接口要求签名和时间戳必须对应,过期后会返回错误 - 确认接口返回的内容编码格式,可在请求配置中添加
responseType: 'utf8'指定编码
内容的提问来源于stack exchange,提问作者李祎丹
相关产品推荐
相关产品推荐

