JavaScipt: Express.js
Ruxin Qu
Posted on October 14, 2022
- Node.js is a runtime environment that allows Javascript files to run outside of browser runtime;
Express.js
is a server-side framework built to work with Node.js -
CRUD
means the api allows clients to create, read, update and delete information. - Require the express module and invoke an instance.
const express = require('express')
const app = express()
-
app.listen(PORT, callback)
can start a server. The first parameter is the port number argument tells the server where to listen; the callback function is executed when the server is listening and ready for response. -
route
is a section of Express code that is associated with an HTTP verb, a url path, and a function that is called to handle that pattern. - Express searches through the routes and responses with the first route matches the request url.
-
path
is part of the requested url after the hostname and port.
HTTP verb(GET,PUT,UPDATE,DElETE)
-
app.get()
is used to match the route with GET request. The first parameter is the route path(string), the second parameter is the callback function to handle the request and send a response. When a requested url arrives,req.params
object will store the information from the requested url path. (query string is not necessary)
app.get('/monsters/:name', (req, res, next) => {
res.send(...); // or res.json() to send json format response
});
//request url : 'monsters/rx' req.params = {name: 'rx'}
-
app.put()
is used to update existing data from the database. It needs data fromquery string
. -
app.post()
is used to create a new resources. It needs data fromquery string
. -
app.delete()
is used to delete a resource. (query string is not necessary)
req.params and req.query
-
route parameter
is in route path and begins with':'
it.req.params
stores route parameters in an object. It is like a unique identifier for the database, so the server can send the requested resource. -
query string
is the part of url after'?'
. Express parse the information intoreq.query
object. The value of the key is a string. It stores information the client send to the server.
Router
- using router can make code cleaner. It adds the router path to the path in
app.use()
Eg:
// in router.js file:
const monserRouter = express.Router()
monsterRouter.get('/:name',(req,res,next)=>{....})
module.exports = monsterRouter;
// in main.js file
const monsterRouter = require('./router.js')
app.use('/monster',monsterRouter)
res.status
💖 💪 🙅 🚩
Ruxin Qu
Posted on October 14, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.