Last active
October 2, 2018 14:18
-
-
Save ganeshkbhat/24221a7fc07605da77c0a1b9be09ef3c to your computer and use it in GitHub Desktop.
ExpressJS Series: Parsing request body using Middlewares
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const bodyParser = require('body-parser'); | |
let app = express(); | |
// parse application/x-www-form-urlencoded | |
app.use(bodyParser.urlencoded({ extended: false })); | |
// parse application/json | |
app.use(bodyParser.json()); | |
const myFirstMiddleware = function(req, res, next) { | |
console.log('My logger'); | |
next(); | |
}; | |
const myRouteMiddleware = function(req, res, next) { | |
console.log('My logger ', 'only for ', req.path); | |
next(); | |
}; | |
const textParser = bodyParser.text({ | |
defaultCharset: 'utf8', | |
inflate: true | |
}); | |
const urlEncodedParser = bodyParser.urlencoded({ | |
extended: true, | |
inflate: true | |
}); | |
// Commonly use raw buffer formats in applications | |
// video/ogg | |
// audio/ogg | |
// application/vnd.ms-excel | |
// application/vnd.openxmlformats-officedocument.spreadsheetml.sheet | |
// application/xhtml+xml | |
// application/zip | |
const rawParser = bodyParser.raw({ | |
inflate: true, | |
limit: '200kb' // Default is 100 kb | |
type: 'application/xml', | |
verify: function(req, res, buf, encoding) { | |
/* Verify that the buffer is not corrupt or that the client is untrustworthy, etc */ | |
} | |
}); | |
app.use(myFirstMiddleware); | |
app.get('/', function(req, res) {res.status(200).send({status: "running", time: Date.now()})}); | |
/* POST */ | |
app.post('/', textParser, myRouteMiddleware, function(req, res) {res.status(200).send({status: "running", time: Date.now()})}); | |
/* PUT */ | |
app.put('/', urlEncodedParser, function(req, res) {res.status(200).send({status: "running", time: Date.now()})}); | |
/* PATCH */ | |
app.patch('/', rawParser, function(req, res) {res.status(200).send({status: "running", time: Date.now()})}); | |
/* DELETE */ | |
app.delete('/', function(req, res) {res.status(200).send({status: "running", time: Date.now()})}); | |
/* OPTIONS */ | |
/* | |
app.options('/', function(req, res) {res.status(200).send({status: "running", time: Date.now()})}); | |
*/ | |
app.post('/api/myform/:categoryId', function(req, res) { | |
res.status(200).send({paramValues: req.params.categoryId, queryParamValues: req.query.create + ' ' + req.query.notify}); | |
}); | |
const host = "127.0.0.1"; | |
const port = 9001; | |
app.listen(host, port, function() {console.log("Server started")}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment