Skip to content

Instantly share code, notes, and snippets.

@ganeshkbhat
Created October 2, 2018 14:25
Show Gist options
  • Save ganeshkbhat/3fefc46ab1383d8508fa44d6cfca5432 to your computer and use it in GitHub Desktop.
Save ganeshkbhat/3fefc46ab1383d8508fa44d6cfca5432 to your computer and use it in GitHub Desktop.
ExpressJS Series: Implementing Helmet middleware
const express = require('express');
const bodyParser = require('body-parser');
const helmet = require('helmet');
let app = express();
// Implementing basic security defaults using helmet
app.use(helmet());
// 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();
};
app.use(myFirstMiddleware);
app.get('/', function(req, res) {res.status(200).send({status: "running", time: Date.now()})});
/* POST */
app.post('/', myRouteMiddleware, function(req, res) {res.status(200).send({status: "running", time: Date.now()})});
/* PUT */
app.put('/', function(req, res) {res.status(200).send({status: "running", time: Date.now()})});
/* PATCH */
app.patch('/', 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