Parsing incoming requests in express.js

Node.jsServer Side ProgrammingProgramming

To receive some data in http request , lets add a form on url path ‘/add-username’:

app.use('/add-username', (req, res,next)=>{
   res.send('<form action="/post-username" method="POST"> <input type="text" name="username"> <button    type="submit"> Send </button> </form>');
});

For parsing the http request, we requires a third party library body-parser: It’s a production required dependency

npm install –save body-parser

express js provides middleware use function to include a body parser before adding middleware.

const http = require('http');

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.urlencoded({extended: false}));

the use(0 function shown above uses next() function by default so http request gets passed to next middleware without any trouble.

The above parser is useful for parsing simple form data like input text etc. but for parsing files, json we will use different parsers.

Now, parsing request is simpler than core node.js way of writing code.

Express.js provides a property body inside the http request which will return request data.

Console output: on localhost: 3000/add-username

data: tutorials point

redirecting request is easy with response has a function redirect.

Complete App.js file is shown here −

const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', (req, res,next)=>{
   next();
});
app.use('/add-username', (req, res,next)=>{
   res.send('<form action="/post-username" method="POST"> <input type="text" name="username"> <button    type="submit"> Send </button> </form>');
});
app.use('/post-username', (req, res, next)=>{
   console.log('data: ', req.body.username);
   res.redirect('/');
});
app.use('/', (req, res,next)=>{
   res.send('<h1> first midleware: Hello Tutorials Point </h1>');
});
const server = http.createServer(app);
server.listen(3000);

After installing any third party library, nodemon should be restarted manually to take effect of new library instead of relying on auto restart of nodemon which might not work properly.

raja
Published on 13-May-2020 16:52:03
Advertisements