kerubim
kerubim

Reputation: 137

How to grab multiform/form-data from a request? Nodejs

I am trying to make an API endpoint that takes in a multipart/form-data.

Currently, I don't have the html written up. But I will most likely make a form that has multiple text inputs, checkboxes, and file upload. I will be sending that form to said API endpoint as multipart/form-data. I am using multipart/form-data because I will be uploading the image to AWS bucket once it hits the API endpoint. Is there something similar to request.body or request.params for grabbing multipart/form-data inside of the request?

I've tried accessing form-data values via POST request.body but body is an empty object.

Routes.js

module.exports = (function() {
   return {
      addProfile: function(req, res){
         try {
           console.log(req.body); // <-- Empty object
           res.status(200).send('yoo');
         } catch (err) {
           res.status(200).send({error:err});
         }
      }
   }
})();

Server.js

var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended: true});
app.use(bodyParser.json());

Upvotes: 1

Views: 989

Answers (1)

dhamo dharan
dhamo dharan

Reputation: 762

Use multiparty middleware to parse uploaded files.

const multiparty = require('multiparty');
    module.exports = (function() {
        return {
          addProfile: function(req, res){
             try {
                var form = new multiparty.Form();
                form.parse(req, function(err, fields, files) {
                    console.log(files);
                    console.log(fields);
                });
               res.status(200).send('yoo');
             } catch (err) {
               res.status(200).send({error:err});
             }
          }
        }
    })();

Upvotes: 1

Related Questions