json - Is there a way to set middleware in express (node.js) to have specific values return in every route? -
the situation referring involves use of json web tokens (jwt). example how automatically add middleware return new json web token if web token expired without duplicating code? sample code below show mean.
var express = require("express"); var jwt = require('jsonwebtoken'); var router = express.router(); router.use(function(req,res,next){ var token = req.body.token || req.query.token; if (token) { jwt.verify(token,"secrettingz",{algorithms:["rs256"]},function(err,decoded){ if (err) { if (token.expired) { // how piece of code run every valid route needs new token without duplicating code? var token = jwt.sign({user:"milnerjenkins"},cert,{algorithm:"rs256",expiresinminutes:1}); req.token = token; next(); }else{ return res.json({message:"failed authenticate token"}); } }else{ req.decoded = decoded; next(); } }) }else{ return res.status(403).send({ message: "no token!" }); } }); apiroutes.get("/stuff",function(req,res){ var token; if (req.token) { token = req.token; }; res.json({message: "dope api son!",token:token}); }); apiroutes.get("/users",function(req,res){ var token; if (req.token) { token = req.token; }; user.find({},function(err,users){ res.json({users: users, token: token}); }); });
as can see code being duplicated in both routes block:
var token; if (req.token) { token = req.token; };
what can express middleware prevent duplication?
the way "middleware" having handler @ end of middlware chain send response. mean handlers have pass request , response down chain. last handler before 404 handler. not recommend attempting that. alternatively can create custom response method express app.
var app = require('express')(); app.response.myjsonres = function(obj) { if (this.req.token) { obj.token = this.req.token; } this.json(obj); }; app.get('/myroute', function(req, res) { // data somehow res.myjsonres(data); });
you coulld change standard json
method.
var prevjson = app.response.json; app.response.json = function(obj) { if (this.req.token) { obj.token = this.req.token; } prevjson.call(this, obj); };
Comments
Post a Comment