Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Last active June 13, 2023 20:20
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save prof3ssorSt3v3/2a196fb1c0f97216516b3a47f51e8c51 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/2a196fb1c0f97216516b3a47f51e8c51 to your computer and use it in GitHub Desktop.
Express JS Routing examples for YouTube video series on Express
//Starter version of the main app.js file
"use strict";
const express = require("express");
const app = express();
const port = process.env.port || 4444;
app.get("/", (req, res) => {
//handle root
});
app.listen(port, err => {
if (err) {
return console.log("ERROR", err);
}
console.log(`Listening on port ${port}`);
});
/**
* "/abc" - handles /abc
* "/ab?cd" - handles /acd or /abcd
* "/ab+cd" - handles /abcd, /abbbcd, /abbbbbbbcd, etc
* "/ab*cd" - "/ab" + anything + "cd"
* /a/ - RegExp: anything that contains "a"
* /.*man$/ - RegExp: anything that ends with "man"
*
*/
//finished version of the app.js file
"use strict";
const express = require("express");
const app = express();
const port = process.env.port || 4444;
const things = require("./routes/things");
app.use(express.json());
app.use("/things", things);
//use the things.js file to handle
//endpoints that start with /things
app.get("/", (req, res) => {
//handle root
res.send("hello root");
});
app.listen(port, err => {
if (err) {
return console.log("ERROR", err);
}
console.log(`Listening on port ${port}`);
});
/**
* "/abc" - handles /abc
* "/ab?cd" - handles /acd or /abcd
* "/ab+cd" - handles /abcd, /abbbcd, /abbbbbbbcd, etc
* "/ab*cd" - "/ab" + anything + "cd"
* /a/ - RegExp: anything that contains "a"
* /.*man$/ - RegExp: anything that ends with "man"
* ^ - starts with
*/
// routes/things.js routing file
"use strict";
const express = require("express");
let router = express.Router();
router.use(function(req, res, next) {
console.log(req.url, "@", Date.now());
next();
});
router
.route("/cars")
.get((req, res) => {
///things/cars
res.send("hi get /things/cars");
})
.post((req, res) => {
res.send("hi post /things/cars");
});
router
.route("/cars/:carid")
.get((req, res) => {
res.send("hi get /things/cars/" + req.params.carid);
})
.put((req, res) => {
res.send("hi put /things/cars/" + req.params.carid);
});
module.exports = router;
@davidislam
Copy link

Very helpful!

@priteshadesa
Copy link

Thank you Sir

@sun2silicon
Copy link

Nice and clean. Thanks

@ChristophBleyer
Copy link

Thanks!

@VJPathak
Copy link

Very helpful for starters., Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment