Using post request in middleware in express


We used use() function to execute middleware’s . Example we used below will be executed for both http GET and POST method −

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);

How to restrict middleware only for GET or only for POST http method etc.

We have http methods like get() and post() etc function similar to use() function.

app.post('/post-username', (req, res, next)=>{
   console.log('data: ', req.body.username); res.redirect('/');
});

In above code snippet we used post() function. It will restrict a http request to only post types for url path ‘/post-username’

get() function

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

Similar to get() and post(), we have delete(), patch, put() functions for respective http requests.

Complete App.js with get() and post()

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.get('/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.post('/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);

Execute : npm start

Browser output −

localhost:300/add-username

localhost:3000/post-username

Updated on: 13-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements