Created
September 22, 2020 15:25
-
-
Save rohanreddych/137c59f7e57edbfbc839dcd440f0daeb to your computer and use it in GitHub Desktop.
Express Routing Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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