Skip to content

Instantly share code, notes, and snippets.

@rohanreddych
Created September 22, 2020 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rohanreddych/137c59f7e57edbfbc839dcd440f0daeb to your computer and use it in GitHub Desktop.
Save rohanreddych/137c59f7e57edbfbc839dcd440f0daeb to your computer and use it in GitHub Desktop.
Express Routing Example
// create a sub-directories called "product" and "products" with filenames like "product{Integer}.html"
//I used two sub dirs just as an example
var express = require("express");
var apiRouter = require("./api_router");
var path = require("path");
var app = express();
app.set("view engine", "ejs");
app.set("views", "views");
app.get("/", function(req, res){
res.render("index", {
message: "rohan dskfnsldk "
});
console.log(req)
});
//This function shows use of Regular Expressions
app.get(/^\/products\/(\d+)$/, (req, res) =>{
var pid = parseInt(req.params[0], 10);
console.log("The customer is asking for product"+pid);
var fileID = "product" + pid + ".html";
var filename = path.join(__dirname, "product", fileID);
res.sendFile(filename);
});
// This shows how to grab parameters from routes.
app.get("/product/:productId", (req, res) => {
var pid = parseInt(req.params.productId, 10);
console.log("ProductID = "+pid);
var fileID = "product" + pid + ".html";
var filename = path.join(__dirname, "product", fileID);
res.sendFile(filename);
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment