前端培训-中级阶段(52)- Express 的安装、使用 Express 完成 RESTful 操作 MongoDB

linong

前端最基础的就是 HTML+CSS+Javascript。掌握了这三门技术就算入门,但也仅仅是入门,现在前端开发的定义已经远远不止这些。前端小课堂(HTML/CSS/JS),本着提升技术水平,打牢基础知识的中心思想,我们开课啦(每周四)。

当我们需要起一个服务器时,我猜大多数人的选择是 Express (至少我看到的一些小工具是)。

今天我们来安装一下,然后结合上节课操作一下 MongoDB

Express

安装

npm install express --save

依赖还是蛮好装的,装好依赖我们就可以启动我们的服务了。

var express = require('express')
var app = express()

var server = app.listen(8088, () => {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at ', host, port);
    console.log('author: lilnong.top');
})

app.use(function(req, res, next){
    res.send('www.lilnong.top')
    next();
})

使用

监听路由、中间件

中间件,监听所有请求类型

app.use(function(req, res, next){
    console.log('use-1', req.ip)
    next();
})

中间件,监听 /api 下的所有请求类型

app.use('/api', function(req, res, next){
    console.log('use-2-/api', req.ip)
    next();
})

监听 /apiGET 请求类型

app.get('/api', function(req, res, next){
    console.log('use-2-/api', req.ip)
    next();
})

监听 /api 下所有请求类型

app.all('/api',function(req, res, next){
    console.log('/api-all', req.ip)
    next();
})

RESTful 实现 CURD

默认 express 是不会解析 post 请求的 body。我们需要增加一个中间件

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

规范

// GET /task 获取 task 列表
// GET /task/:id 查看某个具体的 task
// POST /task 新建一个 task
// PUT /task/:id 更新 id 为 12 的 task
// DELETE /task/:id 删除 id 为 12 的 task

实现代码

const taskrouter = express.Router()
taskrouter.route('/task')
    .post(async (req,res,next) => {
        console.log(req.method, req.url, req.params, req.query, req.body)

        let data = await dbo.collection('user').insert({...req.body,author: 'www.lilnong.top', time: new Date(), uuid: `${Date.now()}-${Math.random()}-${Math.random()}-${Math.random()}`})
        res.send(data)

        
        // fetch(`/restful-api/task`,{
        //     method: 'post',
        //     body: new URLSearchParams({cdate: new Date().toLocaleString()}), 
        // })
        //     .then(v=>v.json())
        //     .then(v=>console.log('post restful-api/task',v))
    })
    .get(async (req,res,next) => {
        console.log(req.method, req.url, req.params, req.query, req.body)

        let data = await dbo.collection('user').find().toArray()
        res.send(data)

        // fetch(`/restful-api/task`)
        //     .then(v=>v.json())
        //     .then(v=>console.log('get restful-api/task',v))
    })
taskrouter.route('/task/:uuid')
    .get(async (req,res,next) => {
        console.log(req.method, req.url, req.params, req.query, req.body)

        let data = await dbo.collection('user').find({uuid: req.params.uuid}).toArray()
        res.send(data)

        
        // fetch(`/restful-api/task/1604050499531-0.7571477556104735-0.2684691266146757-0.455850836469736`)
        //     .then(v=>v.json())
        //     .then(v=>console.log('get restful-api/task/1604050499531-0.7571477556104735-0.2684691266146757-0.455850836469736',v))
    })
    .put(async (req,res,next) => {
        console.log(req.method, req.url, req.params, req.query, req.body)
        
        let data = await dbo.collection('user').updateOne({uuid: req.params.uuid},{$set: {...req.body,utime: new Date()}})
        res.send(data)

        
        // fetch(`/restful-api/task/1604050500761-0.5377497291744571-0.022071316247671557-0.336347246286103`,{
        //     method: 'put',
        //     body: new URLSearchParams({udate: new Date().toLocaleString(), uauthor: 'www.lilnong.top'}), 
        // })
        //     .then(v=>v.json())
        //     .then(v=>console.log('put restful-api/task',v))
    })
    .delete(async (req,res,next) => {
        console.log(req.method, req.url, req.params, req.query, req.body)
        
        let data = await dbo.collection('user').deleteOne({uuid: req.params.uuid})
        res.send(data)

        // fetch(`/restful-api/task/1604050496565-0.660805544561031-0.5097297478722462-0.41065424039611176`,{
        //     method: 'delete',
        // })
        //     .then(v=>v.json())
        //     .then(v=>console.log('delete restful-api/task/1604050496565-0.660805544561031-0.5097297478722462-0.41065424039611176',v))
    })

app.use('/restful-api', taskrouter)

demo 代码

let dbo
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect(
    'mongodb://localhost:27017/sf-mongodb',
    {},
    async function(err, db){
        if(err){
            reject(err)
            return console.error(err)
        }
        dbo = db.db('sf-mongodb');
        console.log('mongodb-success')
    }
)



var express = require('express')
var app = express()

var server = app.listen(process.env.NODE_EXPRESS_MONGODB || 23456, () => {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at ', host, port);
    console.log('author: lilnong.top');
})

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(function(req, res, next){
    console.log('header', req.ip)
    next();
})

app.use('/api',function(req, res, next){
    console.log('/api', req.ip)
    next();
})
app.get('/api',function(req, res, next){
    console.log('/api-get', req.ip)
    next();
})
app.all('/api',function(req, res, next){
    console.log('/api-all', req.ip)
    next();
})

// GET /task 获取 task 列表
// GET /task/:id 查看某个具体的 task
// POST /task 新建一个 task
// PUT /task/:id 更新 id 为 12 的 task
// DELETE /task/:id 删除 id 为 12 的 task
const taskrouter = express.Router()
taskrouter.route('/task')
    .post(async (req,res,next) => {
        console.log(req.method, req.url, req.params, req.query, req.body)

        let data = await dbo.collection('user').insert({...req.body,author: 'www.lilnong.top', time: new Date(), uuid: `${Date.now()}-${Math.random()}-${Math.random()}-${Math.random()}`})
        res.send(data)

        
        // fetch(`/restful-api/task`,{
        //     method: 'post',
        //     body: new URLSearchParams({cdate: new Date().toLocaleString()}), 
        // })
        //     .then(v=>v.json())
        //     .then(v=>console.log('post restful-api/task',v))
    })
    .get(async (req,res,next) => {
        console.log(req.method, req.url, req.params, req.query, req.body)

        let data = await dbo.collection('user').find().toArray()
        res.send(data)

        // fetch(`/restful-api/task`)
        //     .then(v=>v.json())
        //     .then(v=>console.log('get restful-api/task',v))
    })
taskrouter.route('/task/:uuid')
    .get(async (req,res,next) => {
        console.log(req.method, req.url, req.params, req.query, req.body)

        let data = await dbo.collection('user').find({uuid: req.params.uuid}).toArray()
        res.send(data)

        
        // fetch(`/restful-api/task/1604050499531-0.7571477556104735-0.2684691266146757-0.455850836469736`)
        //     .then(v=>v.json())
        //     .then(v=>console.log('get restful-api/task/1604050499531-0.7571477556104735-0.2684691266146757-0.455850836469736',v))
    })
    .put(async (req,res,next) => {
        console.log(req.method, req.url, req.params, req.query, req.body)
        
        let data = await dbo.collection('user').updateOne({uuid: req.params.uuid},{$set: {...req.body,utime: new Date()}})
        res.send(data)

        
        // fetch(`/restful-api/task/1604050500761-0.5377497291744571-0.022071316247671557-0.336347246286103`,{
        //     method: 'put',
        //     body: new URLSearchParams({udate: new Date().toLocaleString(), uauthor: 'www.lilnong.top'}), 
        // })
        //     .then(v=>v.json())
        //     .then(v=>console.log('put restful-api/task',v))
    })
    .delete(async (req,res,next) => {
        console.log(req.method, req.url, req.params, req.query, req.body)
        
        let data = await dbo.collection('user').deleteOne({uuid: req.params.uuid})
        res.send(data)

        // fetch(`/restful-api/task/1604050496565-0.660805544561031-0.5097297478722462-0.41065424039611176`,{
        //     method: 'delete',
        // })
        //     .then(v=>v.json())
        //     .then(v=>console.log('delete restful-api/task/1604050496565-0.660805544561031-0.5097297478722462-0.41065424039611176',v))
    })

app.use('/restful-api', taskrouter)



app.use(function(req, res, next){
    console.log('footer', req.ip)
    res.send('www.lilnong.top')
    next();
})

微信公众号:前端linong

clipboard.png

参考文献

  1. 前端培训目录、前端培训规划、前端培训计划
阅读 799

javascript-lNong
只此一生,何必从众

Read-Search-Ask

21.7k 声望
4.8k 粉丝
0 条评论
你知道吗?

Read-Search-Ask

21.7k 声望
4.8k 粉丝
宣传栏