Skip to content

Instantly share code, notes, and snippets.

@bablukpik
Forked from prof3ssorSt3v3/app1.js
Created March 23, 2022 07:55
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 bablukpik/4870c3f84ad1a1d6cba1be56b5ff91f6 to your computer and use it in GitHub Desktop.
Save bablukpik/4870c3f84ad1a1d6cba1be56b5ff91f6 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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment