关于javascript:前端培训中级阶段52-Express-的安装使用-Express-完成-RESTful-操作-MongoDB

37次阅读

共计 6602 个字符,预计需要花费 17 分钟才能阅读完成。

前端最根底的就是 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

参考文献

  1. 前端培训目录、前端培训布局、前端培训打算

正文完
 0