Parsing Post Form Data Node.js Express

2020-03-02 03:35发布

问题:

I am getting form data in this form

'------WebKitFormBoundarysw7YYuBGKjAewMhe\r\nContent-Disposition: form-data; name': '"a"\r\n\r\nb\r\n------WebKitFormBoundarysw7YYuBGKjAewMhe--\r\n

I'm trying to find a middleware that will allow me to access the form data like:

req.body.a // -> 'b'

I've tried

var express = require('express');
var app = express();


var bodyParser = require('body-parser');

// parse application/x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: false }))

Is there a problem with my implementation or am I not using the correct middleware?

回答1:

The tool that worked was multiparty

app.post('/endpoint', function (req, res) {
    var form = new multiparty.Form();
    form.parse(req, function(err, fields, files) {
        // fields fields fields
    });
})


回答2:

The library which worked for me was express-formidable. Clean, fast and supports multipart requests too. Here is code from their docs

Install with:

npm install -S express-formidable

Here is sample usage:

const express = require('express');
const formidable = require('express-formidable');

var app = express();

app.use(formidable());

app.post('/upload', (req, res) => {
  req.fields; // contains non-file fields 
  req.files; // contains files 
});