Express 基础语法汇总

  • 创建服务器
var express = require('express')
var app = express()

app.listen(3000, () => console.log('Example app listening on port 3000!'))
  • 常用四种路由
app.get('/', function(req, res) {
  res.send('hello world')
})

app.post('/', function(req, res) {
  res.send('Got a POST request')
})

app.put('/user', function(req, res) {
  res.send('Got a PUT request at /user')
})

app.delete('/user', function(req, res) {
  res.send('Got a DELETE request at /user')
})
  • 传参数 parameters
app.get('/users/:userId/books/:bookId', function(req, res) {
  res.send(req.params)
})
  • 处理器 handlers,多个事件顺序执行
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])

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!')
})
  • 中间件 function,requestTime 会传递到下文执行的 req 中
var requestTime = function(req, res, next) {
  req.requestTime = Date.now()
  next()
}

app.use(requestTime)

app.get('/req', function(req, res) {
  var responseText = 'Hello World!<br>'
  responseText += '<small>Requested at: ' + req.requestTime + '</small>'
  res.send(responseText)
})
  • 事件跳转
app.get('/user/:id', function(req, res, next) {
  // if user ID == 0, 跳转到 next route 'special'
  if (req.params.id === '0') 
    next('route')
    // 否则执行这个栈中的下一个中间件函数'regular'
  else 
    next()
}, function(req, res, next) {
  // send a regular response
  res.send('regular')
})

// handler for the /user/:id path, which sends a special response
app.get('/user/:id', function(req, res, next) {
  res.send('special')
})
  • 展示 html 页面
res.sendFile(__dirname + "/public/index.html");
  • 展示静态文件目录
    public 文件夹下的内容
app.use(express.static('public'))
app.use('/static', express.static('public'))
  • 展示 json
app.get("/json", function(req, res) {
    res.json({"message": "Hello World"});
});
  • 错误处理
app.get("/err", function(req, res) {
  throw new Error("BROKEN"); // Express will catch this on its own.
});

app.get("/not", function(req, res, next) {
  fs.readFile("/file-does-not-exist", function(err, data) {
    if (err) {
      next(err); // Pass errors to Express.
    } else {
      res.send(data);
    }
  });
});
  • 404
app.use(function(req, res, next) {
  res.status(404).send("Sorry can't find that!")
})
  • 500
app.use(function(err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})
  • 启动服务器
node index.js

debug 模式启动

$ DEBUG=express:* node index.js

On Windows

> set DEBUG=express:* & node index.js