错误:参数错误,带有node.js请求库的options.body

时间:2018-07-13 13:35:04

标签: node.js request

我正在尝试使用request library从多台(最多两台)打印机中进行打印:

for(var i = 0; i < printers.length; i++) {
  var body = {
    "printerid": printers[i], 
    "ticket": JSON.stringify(ticket),
    "title": "TEST PRINT",
    "content": content,
    "contentType": "text/plain"
  };
  request({
    "method": "POST",
    "url": googlePrintUrl+"submit",
    "headers": {
      "Authorization": "OAuth " + googleAccessToken
    },
    "body": body
  }, function (error, res, body){
    if (error) {
      console.log("There was an error with Google Cloud Print");
      console.log(error);
      return;
    }
    console.log("The server responded with:", body);
  }); 
} 

我收到此错误:

Error: Argument error, options.body.
    at setContentLength (/user_code/node_modules/request/request.js:433:28)
    at Request.init (/user_code/node_modules/request/request.js:438:5)
    at new Request (/user_code/node_modules/request/request.js:127:8)
    at request (/user_code/node_modules/request/index.js:53:10)
    at printByGoogleCloud (/user_code/index.js:211:5)
    at admin.database.ref.once.then.then.then (/user_code/index.js:380:13)

TypeError: First argument must be a string or Buffer
    at ClientRequest.OutgoingMessage.write (_http_outgoing.js:457:11)
    at Request.write (/user_code/node_modules/request/request.js:1495:27)
    at end (/user_code/node_modules/request/request.js:545:18)
    at Immediate.<anonymous> (/user_code/node_modules/request/request.js:574:7)
    at runCallback (timers.js:672:20)
    at tryOnImmediate (timers.js:645:5)
    at processImmediate [as _immediateCallback] (timers.js:617:5)

这似乎与我们使用request库而不是api的方式有关。但是我无法弄清楚到底是什么错误。我已经尝试过对请求进行许多不同的更改,但是都没有奏效。感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

对于您的实际帖子数据,请尝试使用JSON.stringify。

"body" : JSON.stringify(body)

请参阅:Request JSON Payload

或者您可以传递json而不是正文。

json: body

请参阅:JSON HTTP POST Request