文档:https://www.expressjs.com.cn/
安装
npm install express --save
简单使用
const express = require('express')const app = express()const port = 3000// api 访问接口app.get('/', (req, res) => {res.send('Hello World!')})// 监听端口app.listen(port, () => {console.log(`Example app listening at http://localhost:${port}`)})
listen
listten函数内部封装有http模块与https模块,可以看下图
路由
路由方法
// GET method routeapp.get('/', function (req, res) {res.send('GET request to the homepage')})// POST method routeapp.post('/', function (req, res) {res.send('POST request to the homepage')})// 匹配任何get请求app.get('*', function (req, res) {res.send('GET request to the homepage')})等效于app.get( function (req, res) {res.send('GET request to the homepage')})// 匹配所有请求app.all(function (req, res) {res.send('GET request to the homepage')})
路由路径 也就是请求路径
app.get('/about', function (req, res) {res.send('about')})//This route path will match requests to /random.text.app.get('/random.text', function (req, res) {res.send('random.text')})// 动态路由app.get('/list/:id', function (req, res) {res.send('list')})
Route handlers
可以使用或多个路由处理函数,可以使用数组或者函数,这两者可以结合使用
单个回调函数
app.get('/example/a', function (req, res) {res.send('Hello from A!')})
回调函数数组处理路由
var cb0 = function (req, res, next) {console.log('CB0')next()}var cb1 = function (req, res, next) {console.log('CB1')next()}var cb2 = function (req, res) {res.send('Hello from C!')}app.get('/example/c', [cb0, cb1, cb2])
两者结合使用
var cb0 = function (req, res, next) {console.log('CB0')next()}var cb1 = function (req, res, next) {console.log('CB1')next()}app.get('/example/d', [cb0, cb1], function (req, res, next) {console.log('the response will be sent by the next function ...')next()}, function (req, res) {res.send('Hello from D!')})
回调函数中的参数
Request
http://expressjs.com/en/5x/api.html#req
// respond with "hello world" when a GET request is made to the homepageapp.get('/a/:id', function (req, res, next) {console.log('请求头', req.headers)console.log('请求路径', req.path)console.log('请求参数', req.query)console.log('params', req.params) // 获取动态路由的参数res.send('Hello from D!') // 发送响应结果})
Response
http://expressjs.com/en/5x/api.html#res
// respond with "hello world" when a GET request is made to the homepageapp.get('/a/:id', function (req, res, next) {res.status('202')res.setHeader('a', 'aaa');res.send({id: 11,name: 'cnm',age: 18});// 重定向 将其重定向到其他网页// res.status(302).location('https://duyi.ke.qq.com').end();// res.redirect(302, 'https://www.baidu.com') // 直接重定向})
重定向 302 与 301

next
当前回调函数没有结束请求,调用next函数进入下一个回调函数
REST风格API接口
/api/student post 添加学生
/api/student get 获取学生
/api/student put 修改学生
/api/student delete 删除学生
用不同请求方法标明不同的操作类型,接口都一样
