You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Got@11.8.6调用POST/PUT接口时遇RequestError问题求助

问题:Got@11.8.6调用POST/PUT API时出现RequestError错误

环境:Windows 10、Node.js 16.18.1、Got@11.8.6

调用外部POST/PUT接口时触发错误:

GOT package: RequestError: The body option must be a stream.Readable, string or Buffer

代码片段

const gotObject = { method: 'POST', json: true, body: reqBodyObj, headers: reqHeader, };
const apiResponse = await got(microserviceUrl, gotObject);

错误栈

2022-12-19T11:38:44.708Z - error: [D:\Projects\NodeJs\gateway\src\services\microservice.ts] callService  at Request._destroy (D:\Projects\NodeJs\node-api-gateway\node_modules\got\dist\source\core\index.js:1386:21) at _destroy (node:internal/streams/destroy:102:25) at Request.destroy (node:internal/streams/destroy:64:5) at D:\Projects\NodeJs\node-api-gateway\node_modules\got\dist\source\core\index.js:354:26 at processTicksAndRejections (node:internal/process/task_queues:96:5) at Request._finalizeBody (D:\Projects\NodeJs\node-api-gateway\node_modules\got\dist\source\core\index.js:726:23)        at D:\Projects\NodeJs\node-api-gateway\node_modules\got\dist\source\core\index.js:333:28 at new Request (D:\Projects\NodeJs\node-api-gateway\node_modules\got\dist\source\core\index.js:357:11) at makeRequest (D:\Projects\NodeJs\node-api-gateway\node_modules\got\dist\source\as-promise\index.js:35:29)

解决方法

  • Got@11.x版本中,当设置json: true时,需用json字段传递请求体对象,而非body字段——body仅接受流、字符串或Buffer类型,这正是报错的核心原因。
  • 修改代码如下:
const gotObject = { method: 'POST', json: reqBodyObj, headers: reqHeader, };
const apiResponse = await got(microserviceUrl, gotObject);
  • 说明:启用json: true后,Got会自动将json字段的对象序列化为JSON字符串,同时设置Content-Type: application/json请求头;响应也会被自动解析为JSON格式。若同时设置body和json: true,Got会忽略json配置直接使用body,但此时body是对象类型不符合要求,因此触发错误。

内容的提问来源于stack exchange,提问作者Ketav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 13:45:28