node(五)-- express

express的基本使用

使用http模块的问题

1.根据不同的请求路径、处理方法,做不同的事情,处理起来比较麻烦

2.根据请求体和写入响应体是通过流的方式,比较麻烦

常见第三方库

1.express

​ 生态比较完整

2.koa2

​ 技术先进性,接口的友好型比较好

手册

官网:http://expressjs.com

中文网(民间网):https://www.expressjs.com.cn

2.nodemon

手册:https://github.com/remy/nodemon#nodemon

1.自动重启服务器

1.cmd直接启动

npx nodemon index

2.修改package.json文件script字段

npm run "配置参数"

2.配置nodemon.json文件

{
    
    
    "env": {
    
    
      "NODE_ENV": "development"   //开发环境
    },
    "watch": ["*.js", "*.json"],  //修改哪些类型的文件会重启服务
    "ignore": ["package*.json", "nodemon.json", "node_modules", "public"]   //修改哪些文件和文件夹不会重启服务
}

3.express中间件

image-20210329224033828

中间件处理步骤

1.当匹配到了请求

2.交给第一个处理函数处理

3.函数中需要手动的交给后续中间件处理,调用next方法

处理细节

1.如果后续已经没有了中间件

​ express发现如果响应没有结束,express会响应404

2.如果中间件发生了错误

​ 不会停止服务器

​ 相当于调用了 next(错误对象)

​ 寻找后续的错误处理中间件,如果没有,则响应500

3.中间件有响应,则之后的中间件还是需要执行,只是不响应

4.常用中间件

1.express.static()

​ 处理静态伺服

2.express.json()

​ 处理json的数据格式

3.express.urlencoded()

​ 处理字符的数据格式

数组有关面试题

1.map

Array.prototype.sx_map = function (callback) {
    const res = []
    for (let i = 0; i < this.length; i++) {
        res.push(callback(this[i], i, this))
    }
    return res
}

console.log(players.sx_map((item, index) => `${item.name}--${item.num}--${index}`))

2.filter

Array.prototype.sx_filter = function (callback) {
    const res = []
    for (let i = 0; i < this.length; i++) {
        callback(this[i], i, this) && res.push(this[i])
    }
    return res
}

console.log(players.sx_filter(item => item.num >= 23))


3.every

Array.prototype.sx_every = function (callback) {
    let flag = true
    for (let i = 0; i < this.length; i++) {
        flag = callback(this[i], i, this)
        if (!flag) break
    }

    return flag
}

console.log(players.sx_every(item => item.num >= 23)) // false
console.log(players.sx_every(item => item.num >= 0)) // true

4.reduce

Array.prototype.sx_reduce = function (callback, initValue) {
    let start = 0, pre
    if (initValue) {
        pre = initValue
    } else {
        pre = this[0]
        start = 1
    }
    for (let i = start; i < this.length; i++) {
        pre = callback(pre, this[i], i, this)
    }
    return pre
}

// 计算所有num相加
const sum = players.sx_reduce((pre, next) => {
    return pre + next.num
}, 0)
console.log(sum) // 85


猜你喜欢

转载自blog.csdn.net/qq_45256777/article/details/121322234