How to send an object in multipart formData using request in node.js

前提是你 提交于 2019-12-04 07:26:00

The formData attribute doesn't handle objects passed in as a value. see the documentation. A solution would be to use JSON.stringify

var fs      = require('fs');
var request = require('request');
var file    = './test/assets/test.pdf';

var toObj = {
  name: 'joe bob',
  address_1: '123 main st',
  ...
};
var opts = {
  url: 'my_service',
  method: 'POST',
  auth: { user: 'username', password: 'password' },
  json: true,
  formData: {
    front: fs.createReadStream(file),
    to: JSON.stringify(toObj)
  }
};

request(opts, function(err, resp, body) {
  console.log(err, body);
});

note: It's actually the form-data package which supports only strings. Request uses form-data. Here's their usage doc which mentions using "a string, a buffer and a file stream."

I had a similar problem using the request module where everything worked until I added a new line to 'formData'. The only thing that worked for me was to create a string that would be the JSON that would make up the POST body outside of the request and pass it in with 'body' instead of 'formData'.

var postBody = "post body content";

request({
  method: "POST",
  uri: "my_service",
  auth: { user: 'username', password: 'password' },
  body: '{' + postBody + '}',
  ...
}).on("error", function(error){
  ...
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!