Created
April 28, 2020 18:13
-
-
Save CelineChole/388889d80e71c5095a614f24ccf6f978 to your computer and use it in GitHub Desktop.
live demo express part 2
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
const express = require("express"); | |
const app = express(); | |
const morgan = require("morgan"); | |
const path = require("path") | |
const staticMiddleware = express.static(path.join(__dirname, "/public")); | |
app.use((req, res, next) => { | |
console.log(req.method.req); | |
next(); | |
}); | |
app.use(staticMiddleware); | |
app.use(morgan("dev")); | |
app.get("/", (req, res) => { | |
res.send(`<h1>Welcome to my cat website</h1>`); | |
}); | |
app.get("/mycat/:id", (req, res) => { | |
// console.log('id:', req.params.id); | |
// console.log('params:', req.params); | |
res.send(` | |
<pre> | |
a a | |
aaa aaa | |
aaaaaaaaaaaaaaaa | |
aaaaaaaaaaaaaaaaaa | |
aaaaafaaaaaaafaaaaaa | |
aaaaaaaaaaaaaaaaaaaa | |
aaaaaaaaaaaaaaaaaa | |
aaaaaaa aaaaaaa | |
aaaaaaaaaaaaaa | |
a aaaaaaaaaaaaaaaa | |
aaa aaaaaaaaaaaaaaaaaa | |
aaa aaaaaaaaaaaaaaaaaaaa | |
aaa aaaaaaaaaaaaaaaaaaaaaa | |
aaa aaaaaaaaaaaaaaaaaaaaaaaa | |
aaa aaaaaaaaaaaaaaaaaaaaaaaa | |
aaa aaaaaaaaaaaaaaaaaaaaaaaa | |
aaa aaaaaaaaaaaaaaaaaaaaaa | |
aaa aaaaaaaaaaaaaaaaaaaa | |
aaaaaaaaaaaaaaaaaaaaaaaaaa | |
aaaaaaaaaaaaaaaaaaaaaaaaa | |
Awesome cat ${req.params.id} | |
</pre>`); | |
}); | |
// wrong route | |
app.get("/mydog", async (req, res, next) => { | |
try { | |
throw new Error('wrong route, we only like cats here!') | |
} catch (error) { | |
console.log(error.message) | |
next(error) | |
} | |
}) | |
// error handler | |
app.use((err, req, res, next) => { | |
console.error('stack', err.stack) | |
res.status(500).send(`<h1>Oops something went wrong - we are all about cats here! 😿</h1>`) | |
}) | |
// middleware when a route isn't matched - global handler | |
app.use((req, res) => { | |
res.status(404).send(`<h1>Sorry, you got lost! 🙀</h1>`); | |
}); | |
app.listen(3000, () => { | |
console.log("Up and running on port 3000"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment