Skip to content

Instantly share code, notes, and snippets.

@CelineChole
Created April 28, 2020 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save CelineChole/388889d80e71c5095a614f24ccf6f978 to your computer and use it in GitHub Desktop.
Save CelineChole/388889d80e71c5095a614f24ccf6f978 to your computer and use it in GitHub Desktop.
live demo express part 2
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