bjskistad bjskistad - 3 months ago 15
Node.js Question

Use Express Route in If?

Is it possible to use Express to render a user page, if the user is in an array? Something like

var express = require("express");
var app = express();
var users = ["Community", "bjskistad", "sindresorhus"]

app.get(null, function(req, res){
for(var i in array){
if(i in array){
app.get("/"+i, function(req, res){
res.send(//whatever);
}
}
}
}


Is this possible? Or can Express only display static pages?

Answer

A valid approach is

var express = require("express");
var app = express();
var users = ["Community", "bjskistad", "sindresorhus"]

app.get("/:user", function(req, res){ //the username is a path parameter
    var curentUser = req.params.user; //retrieve the username
    if(users.indexOf(currentUser)>-1){ //check if user is in array
        res.send(/*whatever*/);       //send the expected page
        //or 
        //res.redirect(/*whatever else*/); //or redirect to another url
    } else {
        res.send(/*403 page*/);
    }
}