app.js

  1. const express = require("express");
  2. // 本次 http 请求实例
  3. const app = express();
  4. app.use((req, res, next) => {
  5. console.log("请求开始...", req.method, req.url);
  6. next();
  7. });
  8. app.use((req, res, next) => {
  9. // 假设在处理 cookie
  10. req.cookie = {
  11. userId: "abc123",
  12. };
  13. next();
  14. });
  15. app.use((req, res, next) => {
  16. // 假设处理 post data
  17. // 异步
  18. setTimeout(() => {
  19. req.body = {
  20. a: 100,
  21. b: 200,
  22. };
  23. next();
  24. });
  25. });
  26. app.use("/api", (req, res, next) => {
  27. console.log("处理 /api 路由");
  28. next();
  29. });
  30. app.get("/api", (req, res, next) => {
  31. console.log("get /api 路由");
  32. next();
  33. });
  34. app.post("/api", (req, res, next) => {
  35. console.log("post /api 路由");
  36. next();
  37. });
  38. // 模拟登陆验证
  39. function loginCheck(req, res, next) {
  40. // setTimeout(() => {
  41. // console.log("模拟登陆成功");
  42. // next();
  43. // });
  44. setTimeout(() => {
  45. console.log("登陆失败");
  46. res.json({
  47. error: -1,
  48. msg: "登陆失败",
  49. });
  50. });
  51. }
  52. app.get("/api/get-cookie", loginCheck, (req, res, next) => {
  53. console.log("get /api/get-cookie");
  54. res.json({
  55. error: 0,
  56. data: req.cookie,
  57. });
  58. });
  59. app.post("/api/get-post-data", (req, res, next) => {
  60. console.log("post /api/get-post-data");
  61. res.json({
  62. error: 0,
  63. data: req.body,
  64. });
  65. });
  66. app.use((req, res, next) => {
  67. console.log("处理 404");
  68. res.json({
  69. error: -1,
  70. msg: "404 not fount",
  71. });
  72. });
  73. app.listen(3000, () => {
  74. console.log("server is running no port 3000");
  75. });

package.json

  1. {
  2. "name": "express-test",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "index.js",
  6. "scripts": {
  7. "test": "echo \"Error: no test specified\" && exit 1"
  8. },
  9. "keywords": [],
  10. "author": "",
  11. "license": "ISC",
  12. "dependencies": {
  13. "express": "^4.17.1"
  14. }
  15. }