2

My application runs on Nodejs server and Nodejs also acts as a middle ware/proxy for requests originating from the application. So from browser all REST calls goes to NodeJs, and then to Java API.

I see an issue handling requests with multipart-form data.

I intercept the file upload REST call from browser in my nodejs, parse the request using multiparty library, and form a form-data object from the file upload request.

I am using https module to send data to API, so how do I send the form data request to API, via https ?

I send the Content-Type as multipart/form-data; boundary=----WebKitFormBoundary6fyv95baqEpoGJaK, got from browser.

var https = require('https');
var multiparty = require('multiparty');
var FormData = require('form-data');
app.post('/v1/filesUpload', (request, response) => {
let apiOptions ={
    headers: {
     'Content-Type': request.headers['Content-Type'],
      'host' : ...
      'path': ...    
     .
     .
     .
      }
}
let form = new multiparty.Form();
let formdataReq = new FormData();
 Object.keys(fields).forEach(function (name) {
          console.log('got field named ' + fields[name]);
          formdataReq.append(name, fields[name].toString());
        });

        formdataReq.append('file', JSON.stringify(files));    
        const req = https.request(apiOptions, (res) => {

        });    
        req.write(querystring.stringify(formDataReq));
      }catch (e) {
        console.log(e);
      }
    });

});
user2746912
  • 51
  • 1
  • 1
  • 4

2 Answers2

4

try this

const express = require("express");
const app = express();
const bodyParser = require('body-parser');
var multer  = require('multer')();
const FormData = require('form-data');
const axios = require('axios');
const fs = require('fs');

app.use(bodyParser.json());

app.post('/fileUpload' , multer.single('fileFieldName'), (req , res) => {
    const fileRecievedFromClient = req.file; //File Object sent in 'fileFieldName' field in multipart/form-data
    console.log(req.file)

    let form = new FormData();
    form.append('fileFieldName', fileRecievedFromClient.buffer, fileRecievedFromClient.originalname);

    axios.post('http://server2url/fileUploadToServer2', form, {
            headers: {
                'Content-Type': `multipart/form-data; boundary=${form._boundary}`
            }
        }).then((responseFromServer2) => {
            res.send("SUCCESS")
        }).catch((err) => {
            res.send("ERROR")
        })
})

const server = app.listen(3000, function () {
    console.log('Server listening on port 3000');
});
eisbehr
  • 12,243
  • 7
  • 38
  • 63
Rojelo
  • 88
  • 6
  • reference https://stackoverflow.com/questions/52963648/how-to-pass-multipart-request-from-one-server-to-another-in-nodejs/52983731 – Rojelo Mar 11 '20 at 05:38
  • 1
    Thank you so much, when we do a file upload as a form data, apart from the file we also send additional params in the form data like userid, form id, so how do I read both files and fields using Multer? – user2746912 Mar 12 '20 at 16:19
  • 2
    Thanks! FWIW, I had to use `form.getBoundary()` rather than `form._boundary` – Gaff Jun 17 '21 at 22:02
3

I think you need to insert header like that:

const formData = new FormData();

..

await axios.post("{url}", formData, {
      headers: {
        "Content-Type": `multipart/form-data; boundary=${formData.getBoundary()}`,
      },
    });