Mustafa
Mustafa

Reputation: 10413

Nodejs, Express getting request parameters at the beginning

I am building a web application, in which most requests to server, an identifier-data object mapping needs to be made. I want to override wherever a request is handled like this, but I do not want to write mapping to each request, is there a better way?

var express = require("express");
var app = express();


function mapping(req,res,next){
    console.log(req.params); 
    // actual data fetch from server depending on req.params
    // Example, if req.params.userid defined -> fetch userid from db and place it
    if ( req.params.userid){
        req.user = {
            name: "Mustafa",
            title: "Student"
        }
    }
    next();
}

app.get("/:userid", mapping, function(req,res){
    res.send(req.user);
});

app.listen(3000);

Upvotes: 0

Views: 262

Answers (2)

go-oleg
go-oleg

Reputation: 19480

You can use app.param to have the middleware apply specifically to routes where userid is present:

function mapping(req,res,next,userId){
    console.log(req.params); 
    // actual data fetch from server depending on req.params
    // Example, if req.params.userid defined -> fetch userid from db and place it
    if (userid){
        req.user = {
            name: "Mustafa",
            title: "Student"
        }
    }
    next();
}

app.param( "userid", mapping );

app.get("/:userid", function(req,res){
    res.send(req.user);
});

Upvotes: 3

tuxedo25
tuxedo25

Reputation: 4828

You just need to app.use() mapping. Since it always calls next(), it will defer to the next route once its work is finished.

// always use 'mapping' middleware.
app.use(mapping);

// handle GET /{userid}
app.get("/:userid", function(req,res){
    res.send(req.user);
});

Upvotes: 2

Related Questions