mikeym
mikeym

Reputation: 6331

request.post in Node throws { code: undefined, reason: 'Argument error, options.body.' }

I am getting the following error when trying to perform a request.post. It's confusing because it seems to be first referring to the body of my options but then complains about the first argument should be a string or buffer.

{ code: undefined, reason: 'Argument error, options.body.' } DOH! _http_outgoing.js:454 throw new TypeError('first argument must be a string or Buffer'); ^ TypeError: first argument must be a string or Buffer

I tried changing the url value to a string but that doesn't fix it.

Here is what my code looks like. As you can see I've logged out the reqOptions and have verified that the url is definitely being passed to the request.postso I am not sure what the problem is. Cheers for any help!

var reqOptions = {
    url: options.host, 
    body: formData,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  };
  console.log('CHECK OPTIONS :: ', reqOptions); 
  request.post(reqOptions, function (err, resp) {...}

Upvotes: 1

Views: 1030

Answers (2)

Sajeenthiran
Sajeenthiran

Reputation: 427

add json : true

  request({
    url : url,
    method :"POST",
    headers : {
        "content-type": "application/json",
    },
    body: body,
    json: true
},

Upvotes: 0

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123533

If formData is an object, you'll probably want to use request's form: option instead of body:. That will both stringify the object and set the Content-Type header.

var reqOptions = {
  url: options.host, 
  form: formData
};
console.log('CHECK OPTIONS :: ', reqOptions);
request.post(reqOptions, function (err, resp) {...});

The body: option expects a value that is either a string, Buffer, or ReadStream. Without using form:, you'll have to stringify the object yourself.

var qs = require('querystring');

var reqOptions = {
  url: options.host, 
  form: qs.stringify(formData),
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
};

Upvotes: 1

Related Questions