This is the 22nd day of my participation in the August More Text Challenge

What is Express?

Express is a fast, simple and minimalist Node.js Web application development framework. Through it, you can easily build various Web applications. For example,

  • Interface services
  • Traditional Web sites
  • Development tool integration, etc

Express itself is minimalist and provides only the basics of Web development, but it integrates many external plug-ins to handle HTTP requests through middleware placement

Express

1. NPM I Express This is the most common method format after a good package

const express = require('express')
const app = express()

app.get('/'.(req,res) = >{
    res.send('hello word')
})
app.post('/'.(req,res) = >{
    res.send('post /')
})
app.put('/user'.(req,res) = >{
    res.send('put user')
})
app.delete('/user'.(req,res) = >{
    res.send('delete user')
})

app.listen(3000.() = >{
    console.log('service 55555555');
})
Copy the code
  • App is an instance of Express
  • METHOD is the lowercase HTTP request METHOD
  • PATH is the PATH on the server
  • HANDLER is the function that is performed when route matching is performed

app.METHOD(PATH,HANDLER)

Express does not secondary abstract the existing features of Node.js, but merely extends the basic content needed for Web applications on top of it

  • The HTTP module is still used internally
  • The request object inherits fromhttp.lncomingMessage
  • The response object inherits fromhttp.ServerResponse

The request object

The REQ object represents the HTTP request and has properties such as the request query string, parameters, body, HTTP label, and so on (the HTTP response is RES), but the actual name is determined by the parameters of the callback function you are using

The response object

The RES object represents the HTTP response that the Express application sends when it receives an HTTP request.

Request Demo Case

const express = require('express')
const app = express()

const fs = require('fs')
const { promisify } = require('util')
const path = require('path')

const redFile = promisify(fs.readFile)
const waritFile = promisify(fs.writeFile)
const dbPath = path.join(__dirname,'.. /db.json')

getDb = async() = > {const data = await redFile(dbPath,'utf-8')
    return JSON.parse(data)
}
saveDb = async db => {
    const db1 = JSON.stringify(db,null.' ')
    await waritFile(dbPath,db1)
}

// Configure the parse form request body: application/json
app.use(express.json())

Application /x-www-form-urlencodede
app.use(express.urlencoded())


app.get('/user'.async (req,res)=>{
    try{
        const db = await getDb()
        res.status(200).json(db.todos)
    }catch(err){
        res.status(500).json({
            error: err.message
        })
    }
})
app.post('/user/:id'.async (req,res)=>{
    try{
        const db = await getDb()
        const find = db.todos.find(_= >_.id === req.params.id - 0)
        if(! find)return res.status(404).end()
        res.status(200).json(find)
    }catch(err){
        res.status(500).json({
            error: err.message
        })
    }
})

app.post('/user'.async (req,res)=>{
    let body = req.body
    if(! body.title)return res.status(422).json({error:'give me the title'})
    try{
        const db = await getDb()
        const length = db.todos[db.todos.length-1].id ? db.todos[db.todos.length-1].id + 1: 1
        const data = {
            'id':length,
            'title': body.title
        }
        db.todos.push(data)
        await saveDb(db)
        res.status(200).json(data)

    }catch(err){
        res.status(500).json({
            error: err.message
        })
    }
})

app.patch('/user/:id'.async(req,res)=>{
    let body = req.body
    try{
        const db = await getDb()
        const find = db.todos.find(_= >_.id === req.params.id - 0)
        if(! find)return res.status(404).end()
        Object.assign(find,body)
        await saveDb(db)
        res.status(200).json(Object.assign(find,body))

    }catch(err){
        res.status(500).json({
            error: err.message
        })
    }
})
app.delete('/user/:id'.async(req,res)=>{
    let id = req.params.id - 0
    try{
        const db = await getDb()
        const find = db.todos.findIndex(_= >_.id === id)
        console.log(find);
        if(find === -1) return res.status(404).end()
        db.todos.splice(find,1)
        await saveDb(db)
        res.status(204).end()

    }catch(err){
        res.status(500).json({
            error: err.message
        })
    }
})

app.listen(3000.() = >{
    console.log('service 55555555');
})
Copy the code