简体   繁体   中英

Sending form data in nodejs using https.request

I am trying to post a request with my nodejs server to another server and then I have to save response in a file. I am using nodejs https.request module.

This is my request:

    var formData = new FormData();
    formData.append('first',3);
    formData.append('second', '25');
    formData.append('source_file', fs.createReadStream(sourcefile));
    formData.append('source_image', fs.createReadStream(sourceimage));

var options = {
    hostname: 'ip',
    path: '/api/path',
    method: 'POST'
}
var file = fs.createWriteStream("file.pdf");
var req = https.request(options, (response) => {
    response.pipe(file);
    console.log("File saved");
    response.send("done")
  });

  req.on('error', (e) => {
    console.error(e);
  });

  req.write(formData);
  req.end();

But I am getting the error

First argument must be a string or Buffer

I tried sending my files using formData.toString() but on using this, error disappears but My files are not working and also I have sent data like this:

 var formData = new FormData();
formData = {
        first: 3,
        second: '25',
        source_file: fs.createReadStream(sourcefile),
        source_image: fs.createReadStream(sourceimage)
    };

How can I send my files to other server using this request.

Thanks

I assume you are using form-data . To fix the First argument must be a string or Buffer error replace:

req.write(formData);
req.end();

with

formData.pipe(req);

( formData behaves like a Node.js ReadableStream )

You should also add headers to your request:

var options = {
    hostname: 'ip',
    path: '/api/path',
    method: 'POST',
    headers: formData.getHeaders()
}

Source: https://github.com/form-data/form-data#alternative-submission-methods

I once faced an issue similar to this. I resolved it using the form-data package available on NPM here with the axios package here

the snippet below worked for me

const FormData = require("form-data");
const axios = require("axios");

const form = new FormData();
form.append("first", 3);
// other data should go here
form.append("file", fs.createReadStream("filePath"));

axios({
  method: "post",
  url: "url",
  data: form,
  headers: { ...form.getHeaders() }
});

You can use node inbuilt body-parser module to parse the form data into JSON and you have to use app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); And when you do req.body then it will your form data into an object form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM