如何修复 NodeJS request Error: Argument error, options.body

问题:

你正在使用 request 发送一个应该进行 JSON 编码的 POST 请求,但遇到类似这样的错误:

request_error_example.txt
Error: Argument error, options.body.
    at setContentLength (/home/uli/myproj/node_modules/request/request.js:434:28)
    at Request.init (/home/uli/myproj/node_modules/request/request.js:439:5)
    at new Request (/home/uli/myproj/node_modules/request/request.js:128:8)
    at request (/home/uli/myproj/node_modules/request/index.js:53:10)
    at Function.post (/home/uli/myproj/node_modules/request/index.js:61:12)

此外,还有此堆栈跟踪:

request_typeerror_trace.txt
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer
    at write_ (_http_outgoing.js:647:11)
    at ClientRequest.write (_http_outgoing.js:622:10)
    at Request.write (/home/uli/myproj/node_modules/request/request.js:1501:27)
    at end (/home/uli/myproj/node_modules/request/request.js:546:18)
    at Immediate.<anonymous> (/home/uli/myproj/node_modules/request/request.js:575:7)
    at runCallback (timers.js:763:18)
    at tryOnImmediate (timers.js:734:5)
    at processImmediate (timers.js:716:5)

解决方案

错误基本上告诉你 request 无法确定 body 的长度,因为你没有告诉它如何编码 body,而且它不是简单的字符串或缓冲区。解决方案是通过在 options 参数(request.post 的第一个参数)中添加 json: true 来告诉 request 使用 JSON body 编码。有效的 options 参数如下所示:

request_json_opts.js
const opts = {
    url: 'http://localhost:1234/api/myapi',
    body: {/* 你的 body 对象 */},
    json: true // <-- 添加此行
};

Check out similar posts by category: Javascript, NodeJS