从路由中获取参数

  1. app.route('/projects/:projectId/test_targets')
  2. .all(function(req, res, next) {
  3. const projectId: string = req.params.projectId;
  4. next();
  5. })

route的应用

  1. app.route('/projects/:projectId')
  2. .all(function(req, res, next) {
  3. const projectId: string = req.params.projectId;
  4. let project;
  5. /* 获取project*/
  6. if (project === undefined) {
  7. res.send({ status: -1, msg: '项目id无效' });
  8. return;
  9. }
  10. res.locals.project = project;
  11. next();
  12. })
  13. .get(function(req, res) {
  14. let project = res.locals.project;
  15. /* 获取项目数据*/
  16. res.send({ status: 0, msg: '获取项目数据成功', data: project });
  17. })
  18. .put(function(req, res, next) {
  19. let project = res.locals.project;
  20. /* 更新代码*/
  21. res.send({ status: 0, msg: '修改项目成功', data: project });
  22. next();
  23. })
  24. .delete(function(req, res, next) {
  25. let project = res.locals.project;
  26. /* 删除代码*/
  27. res.send({ status: 0, msg: '删除项目成功', data: project });
  28. next();
  29. })
  30. .all(function(req, res) {
  31. /* 持久化代码*/
  32. });

res.locals可以保存一些临时数据,可在一系列的中间件之间传递.
对比app.locals,app.locals是对app中所有中间件有效,而res.locals则仅对处理当前请求的中间件有效.