Forms are widely used in the web to submit or fetch some information for the visitors. Multipart/form-data is a type of encoding. It is important to note that it works only with POST method. This is also important while using uploading files. Without this, you can’t upload files using form. The uploaded files will not be encoded.
Firstly go to terminal/cmd and use the below code to install the body-parser(for parsing JSON and URL-encoded data) and multer(for parsing multipart/form-data) middleware.
npm install --save body-parser multer
Express.js is the most popular web development Node js framework.
There are two major aspects to HTML forms:-
- GET requests.
- POST requests.
Let’s see how we can manage Get & Post requests in Express –
GET Requests In Express
There are two processes of passing parameters to an Express application they are:-
- Named placeholders
- GET parameters.
Named Placeholders
Named Placeholders are defined in express route & URL and are used for relaying information to the app.js file.
A named placeholder can be defined and accessed in this way:
app.get('/user/:id', function(req, res) {
res.send('user ' + req.params.id);
});
GET Parameters
The second method of sending information to app.js file(backend) is through querstring in URL via GET parameter.
For example, If this is the URL
http://localhost/books?category=biographies&type=paperback
you access the GET parameters in Express, this way:
console.log('Category: ' + req.query['category']);
console.log('Type: ' + req.query['type']);
Handle / Process POST requests in Express
The POST request method also has two aspects:
- Text data
- File uploads.
Let’s see how to handle POST request method in Express –
Text Data
We can access text data via POST requests using the body-Parser middleware in Express. We can use app.use (express.bodyParser()) .
We can explain this by an example:-
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
You can access the POST submitted text data in this way:
console.log('Username: ' + req.body.username);
console.log('Password: ' + req.body.password);
File Uploads
File uploads in Express are not that straightforward, But it isn’t that complicated either, you just need to do a few things and you will be all set up to handle file uploads.
First of all, you will need to install connect-form.
$ npm install connect-form
[email protected] ./node_modules/connect-form
+-- [email protected]
var form = require('connect-form');
var fs = require('fs'); var busboy = require('connect-busboy'); //... app.use(busboy()); //... app.post('/fileupload', function(req, res) { var fstream; req.pipe(req.busboy); req.busboy.on('file', function (fieldname, file, filename) { console.log("Uploading: " + filename); fstream = fs.createWriteStream(__dirname + '/files/' + filename); file.pipe(fstream); fstream.on('close', function () { res.redirect('back');
}));
}); }); });
Update HTML Form:
<form method="post" enctype="multipart/form-data" action="/file-upload">
<input type="text" name="username">
<input type="password" name="password">
<input type="file" name="thumbnail">
<input type="submit">
</form>
The update method is set to post and enctype to multipart/form-data, else file uploads just won’t work.
It is most important to note that if your form is enctype to multipart/form-data, you will no longer be able to access the post data from req.body!
Note– enctype is used to encode the data. It’s a kind of translating the original data to another format.
Express route and an example code to perform the above form:
app.post('/file-upload', function(req, res, next) {
req.form.complete(function(err, fields, files) {
if (err) { next(err); }
else {
console.log(fields);
console.log('---------------');
console.log(files);
res.redirect(req.url);
}
});
});
Both the described ways are quick and easy to take form-data. You can go with whichever you find easy and comfortable to understand.
Learn More: