# ExpressJS - Clone the project - git@github.com:icesplendent/TutorialExpress.git ## Prerequisite - What we need - nodemon - express - cors - cross-env - dotenv - uuid - moment ## Get Started ```javascript= const express = require('express'); const app = new express(); const PORT = process.env.PORT || 8000; app.listen(PORT, () => console.log(`Server is running at PORT ${PORT}`)) ``` ## Set Static folder ```javascript= app.use(express.static(path.join(__dirname, 'public'))); ``` ## Middleware ```javascript= // middleware const logger = (req, res, next) => { console.log(`${req.protocol}://${req.get("host")}${req.originalUrl}`); next(); // the next function to go }; // Init middleware app.use(logger); ``` ## [Body Parser](https://ithelp.ithome.com.tw/articles/10241083) ```javascript= app.use(express.json()); ``` ## Learn from the Code ```javascript= app.get("/api/member/:id", (req, res) => { const found = member.some((x) => x.id === parseInt(req.params.id)); if (found) { res.json( member.filter((member) => member.id === parseInt(req.params.id)) ); } else { res.status(400).json({ msg: `no id with ${req.params.id}` }); } }); ``` - `:id`: a URL parameter - `req.params.id` returns a `String`. Convert it back to number - `res.status(400)`: send the status - `req.json()`: parses incoming requests with JSON payloads ## urlendcode Reference - https://blog.tedshd.io/page/3/ -
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up