Express 快速入门

安装 Express

mkdir express-playground
cd express-playground

npm init -y
npm i express

Hello world

import express from 'express'

const app = express()

app.get('/', (req, res) => {
    res.send('Hello, world')
})

app.listen(3000, () => {
    console.log('http://127.0.0.1:3000')
})

请求参数

属性 描述
app 对 app 对象的引用
hostname Host 请求头定义的主机名
ip 客户端 ip
method HTTP 方法
protocol 请求协议
path 请求路径
query 查询字符串参数
params 路径参数
body 包含在请求体的数据
cookies 请求携带的 cookies
signedCookies 请求携带的签名的 cookies

服务端向客户端发送响应

res.send()

send 方法,如果传入的是字符串,则会自动将 Content-Type 设置为 text/html;如果传入的是数组或对象,则会将 Content-Type 设置为 application/json,并会将数组或对象解析为 JSON 格式。

send 方法调用完毕后会自动关闭连接。

另一种发送响应的方式是 res.end(),参数必须是字符串或 Buffer 类型,它不会主动设置 Content-Type

设置 HTTP 状态码

res.status(404)
// do something

res.status(404).end()

res.status(404).send('Not Found')

res.sendStatus(404)
// 相当于 res.status(404).send('Not Found')

发送 JSON 响应

res.json({ username: 'tom' })

Cookie 管理

获取 cookie(TODO)

设置 cookie

// 设置 cookie
res.cookie('sessionId', 'xxx')

// 配置选项
res.cookie('sessionId', 'xxx', {
  domain: '.flaviocopes.com',
  path: '/administrator',
  secure: true,
  expires: new Date(Date.now() + 900000),
  httpOnly: true
})

清除 cookie

res.clearCookie('sessionId')

处理 HTTP header

获取 header

// 一个对象,包含所有请求头,key 为小写字母 + 下划线的组合
res.headers

// 获取指定的请求头
res.header('Content-Type')

设置 header

res.set('Content-Type', 'text/html')

// 针对于 Content-Type 标头的快捷设置方式
res.type('html') // text/html
res.type('json') // application/json
res.type('application/json') // 同上
res.type('png')  // image/png

重定向

// 302 临时重定向
res.redirect('/xxx')

// 301 永久重定向
res.redirect(301, '/xxx')

// 重定向到 Referrer 标头值
res.redirect('back')

路由

TODO

模板引擎

TODO

中间件

TODO

静态文件服务

app.use(express.static('public'))

向客户端发送文件(文件下载)

res.download('./file.txt')

// 自定义文件名
res.download('./file.txt', '好康的.mp4')

// 文件发送后的回调
res.download('./file.txt', '好康的.mp4', err => {
    if (err) {}
    else {}
})

session 会话

TODO

表单验证

TODO

参考资料

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注