You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# setup a basic package.json
$ npm init -y
# install express
$ npm i express
# nodemon, make dev a lot easier
$ npm i --save-dev nodemon
we use nodemon to resert our save anytime we make changes
in package.json
"scripts": {
"devStart": "nodemon server.js"
}
run our server
$ npm run devStart
>[email protected] devStart
> nodemon server.js
[nodemon] 2.0.20
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
[nodemon] clean exit - waiting for changes before restart
make some changes to the empty server.js
console.log("Hi")
you will see the server restart automatically
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Hi
[nodemon] clean exit - waiting for changes before restart
create express server
constexpress=require('express');constapp=express();constport=3000;app.get('/',(req,res)=>{console.log('get / log')res.send('Hello World!')// testing });app.get("/users",(req,res)=>{res.send("User List");});app.get("/users/new",(req,res)=>{res.send("New User");});app.listen(port,()=>console.log(`Example app listening on port ${port}!`));
for the most part res.send() is not something you're going to use very often.
it's great for testing purposes.
but generally you want to use a more specific things.
res.sendStatus(500)// both status and messageres.status(500).send("hi")// more commonly, send a jsonres.status(500).json({message: "Error"})// send a file to user to downloadres.download('<path_2_file>')// render html file// need extra view engine to work // e.g. `npm i ejs`app.set('view engine','ejs')// ...res.render('index')// rename index.html to index.ejs to work
// get user by idrouter.get("/:id",(req,res)=>{res.send(`Get User by id ${req.params.id}`);});// update user by idrouter.put("/:id",(req,res)=>{res.send(`Update User by id ${req.params.id}`);});// delete user by idrouter.delete("/:id",(req,res)=>{res.send(`Delete User by id ${req.params.id}`);});
user route() method simplify it
router.route('/:id').get((req,res)=>{res.send(`get user by id ${req.params.id}`);}).put((req,res)=>{res.send(`update user by id ${req.params.id}`);}).delete((req,res)=>{res.send(`delete user by id ${req.params.id}`);});
router.param middleware
router.param() function is going to run anytime it finds a param that matches the name you pass in. for exampe, the parameter id in our /users/:id request
router.param('id',function(req,res,next,id){console.log(id)next()// going on to the next piece of middleware.});
.param() here is essentially a type of middleware.