Express.js

2024/1/27

# express 框架

# 简单用法及 API

  1. 安装expressnodemon,使用 CommonJS .mjs 后缀。
  2. 使用express-validator进行参数等的校验,链式 api 调用,可以校验一个参数,也可以用数组的形式同时校验多个
  3. 使用 schame 统一配置校验 fields
  4. 使用中间件即类似(req, req, next)=>{...; next();}这种,可以处理数据等。抽离业务逻辑。最后要记得next(),否则会 block 住。可以同时接收多个中间件,会依次执行。
  5. 使用 use 注册中间件、路由等。
  6. 使用路由统一管理相似业务逻辑
  7. 前一个中间件修改 req 和 res 之后,后面的中间件可以接收到修改后的 req 和 res
  8. 使用一个 index 集中注册路由,然后在入口文件中只需注册一次。
  9. 使用cookie-parser解析 cookie
  10. 使用express-session解析 session
  11. 使用passport实现登录验证
  12. 使用multer处理上传文件
  13. 使用cors解决跨域问题
  14. 使用morgan日志记录
  15. 使用dotenv读取环境变量
  16. 使用body-parser解析请求体
  17. 使用mongoose操作数据库
  18. 使用mongodb操作数据库
  19. 使用bcrypt加密密码
  20. 使用jsonwebtoken生成 token
  21. 使用express-rate-limit限制请求频率
  22. 使用helmet设置安全相关的 HTTP 头
  23. 使用compression压缩响应体
  24. 使用connect-mongo将 session 存储到 mongodb 中
  25. 接入OAUTH2.0,使用passport-oauth2passport-google-oauth20passport-facebook
  26. 使用jest进行单元测试
  27. 使用
  28. 使用
  29. 简单 demo:
import express from "express";
import {query, body, validationResult, matchedData, checkSchema } from "express-validator";
import cookieParser from "cookie-parser";
import session from "express-session";
import passport from "passport";
import mongoose from "mongoose";
import MongoStore from "connect-mongo";
import usersRouter from "./router/user.mjs";
import {userValidationSchemas} from "./validation/validationSchemas.mjs";
import {mockUsers} from "./mock/users.mjs";
import "./passport-local.mjs";
import {User} from "./mongoose/schemas/user.mjs";
import {hashPassword} from "./utils/helper.mjs";

// 注册passport策略
// passport.use(require("./local-strategy.mjs"));

const app = express();

// 27017
mongoose.connect("mongodb://localhost/test", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true
}).then(() => {
  console.log("Connected to MongoDB");
}).catch(err => {
  console.log("Error connecting to MongoDB", err);
});


// 注册路由
app.use(express.static("public"));

// 注册中间件
app.use(express.urlencoded({ extended: true }));

app.use(cookieParser("xxx"));

app.use(passport.initialize());
app.use(passport.session());

app.post("/api/auth", passport.authenticate("local"), (req, res) => {
  res.status(200).send(req.user);
});

app.use(session({
  secret: "xxx",
  saveUninitialized: false, // 是否自动保存未初始化的会话,建议false
  resave: false,
  cookie: {
    maxAge: 60*60*1000
  },
  // MongoStore: MongoStore.create({
  //   mongoUrl: "mongodb://localhost/test",
  //   collectionName: "sessions"
  // })
  // 使用connect-mongo把session存储到mongodb中,这样就可以重启服务后不会丢失session
  store: MongoStore.create({
    client: mongoose.connection.getClient(),
  })
}));
// 使用use注册路由
app.use(usersRouter);
const PORT = process.env.PORT || 3000;

// 用中间件接收json格式数据,使用了中间件之后仍然可以继续处理
app.use(express.json(), (req, res, next)=>{
  // ...
  next();
}, (req, res, next)=>{
  // ...
  next();
}, ...);

app.get("/", (req, res, next) => {
  // visited = true,使用同一个sessionId
  req.session.visited = true;
  // 设置cookie,signed:加签名的
  res.cookie("Test", "test content", {maxAge: 6000, signed: false});
  res.status(200).send({ msg: "Hello world" });
});

app.post("/api/auth", (req,res)=>{
  const {
    body:{username, password}
  }=req;
  const findUser = mockerUsers.find(user=>user.username===username);
  if(!findUser||findUser.password!==password){
    return res.status(401).send({msg:"need auth"});
  }
  req.session.user = findUser;
  return res.status(200).send(findUser);
});

// 通过这个接口可以获取当前用户的session信息,即登录状态
app.get("/api/auth/status", (req, res, next) => {
  req.sessionStore.get(req.sessionID, (err, session)=>{
    console.log(session);
  });
  return req.session.user? res.status(200).send(req.session.user) : res.status(401).send({msg:"need auth"});
});

app.post("/api/cart", (req, res)=>{
  if(!req.session.user){return res.sendStatus(401);}
  const {body: item} = req;
  const {cart} = req.session;
  if(cart){
    cart.push(item);
  }else{
    req.session.cart = [item];
  }
  return res.status(201).send(item);
});

app.get("/api/cart", (req, res)=>{
  if(!req.session.user){return res.sendStatus(401);}
  const {cart} = req.session;
  if(!cart){
    return res.status(200).send([]);
  }
  return res.status(200).send(cart);
});

app.get("/api/users",
  query("name").isString().notEmpty().isLength({min: 3, max: 32}).withMessage("这里填检验失败的报错信息"),
  (req, res, next) => {
    // 打印原始cookie
    console.log(req.headers.cookie);
    // 打印session
    console.log(req.session);
    // 假设有个sessionID
    req.sessionStore.get(req.session.id, (err, sessionData) => {
      if(err){
        console.log(err);
        throw err;
      }
      console.log(sessionData);
    });
    // 打印利用中间件处理过的parsed cookie
    console.log(req.cookies);
    console.log(req.signedCookies);
    res.status(200).send({ msg: "Hello world" });
  }
);

app.get("/api/users/:id", (req, res, next) => {
  console.log(req.params); // 接收路径参数
  console.log(req.query); // 接收查询参数
  // 如果参数有误,可以直接
  // return res.sendStatus(400);
  res.status(200).send({ msg: "Hello world" });
});

// post mockdata
app.post("api/users",
  // 校验方法1
  // body("username").notEmpty().withMessage("username not empty").isLength({min: 3, max: 32}).withMessage("length should be xx")
  // .isString().withMessage("should be string"),
  // body("age").isNumber().withMessage("xxx"),// 类似field校验,可以分开也可以一起写到一个[]中
  // 校验方法2
  checkSchema(userValidationSchemas),
  (req, res) => {
    // 接收上面的校验结果
    const result = validationResult(req);
    if(!result.isEmpty()){
      return res.status(400).send({errors:result.array()});
    }
    const body = req.body;
    const data = matchedData(req);

    return res.status(200).send(data);
  }
);

// post database mongoose
app.post(
  "/api/users",
  checkSchema(userValidationSchemas),
  async (req, res) => {
    const result = validationResult(req);
    if (!result.isEmpty()) {
      return res.status(400).send({ errors: result.array() });
    }
    const data = matchedData(req);
    // const {body} = req;
    // 加密密码
    data.password = await hashPassword(data.password);
    const user = new User(data);
    try {
      const savedData = await user.save();
      return res.status(201).send(savedData);
    } catch (err) {
      return res.status(400).send({ msg: "save failed" });
    }
  }
);

app.post("/api/auth/logout", (req, res) => {
  if (!req.user) {
    return res.sendStatus(401);
  }
  req.logout(err => {
    if (err) {
      console.log(err);
      return res.status(500).send({ msg: "logout failed" });
    }
    res.status(200).send({ msg: "logout success" });
  });
});

// patch: 只更新某部分数据
// put: 更新全部数据
// delete

app.listen(PORT, () => {
  console.log(`App is running on Port ${PORT}`);
});


// validationSchemas.mjs
export const userValidationSchemas = {
  username:{
    isLength:{
      options:{
        min:5,
        max:32
      },
      errorMessage:"should be xxx"
    },
    notEmpty:true,
    isString:{
      errorMessage:"should be string"
    }
  },
  age:{},
  // ...
}

// user.mjs
import {Router} from 'express';
const router = Router();// mini app,用法和express App几乎一样

router.get("/api/user", ()=>{});
router.get("/api/user/:id", ()=>{});
router.post("/api/user", ()=>{});
router.put("/api/user/:id", ()=>{});
router.patch("/api/user/:id", ()=>{});
router.delete("/api/user/:id", ()=>{});

export default router;

// local-strategy.mjs
import passport from "passport";
import { Strategy } from "passport-local";
import { mockUsers } from "./mock/users.mjs";
import { User } from "./mongoose/schemas/user.mjs";
import { comparePassword } from "./utils/helper.mjs";
passport.serializeUser((user, done) => {
  done(null, user.id);
});


passport.deserializeUser(async(id, done) => {
  console.log(`Inside Deserializer`);
  console.log(`Deserialize User ID: ${id}`);
  try {
    const user = await User.findById(id);
    // const user = mockUsers.find(user => user.id === id);
    if (!user) {
      throw new Error("user not found");
    }
    done(null, user);
  }catch (err) {
    done(err, null);
  }
});

export default passport.use(
  new Strategy(
  //  {
  //    usernameField: "username",
  //    passwordField: "password"
  //  },
    async (username, password, done) => {
      console.log(`username: ${username}, password: ${password}`);
      try {
        const findUser = await User.findOne({username});
        if(!findUser){
          throw new Error("user not found");
        }
        // if(findUser.password!==password){
        if(comparePassword(password, findUser.password)){
          throw new Error("password not match");
        }
        done(null, findUser);
      } catch (err) {
        done(err, null);
      }
    //  const user = mockUsers.find(user => user.username === username && user.password === password);
    //  if (!user) {
    //    return done(null, false, { message: "Incorrect username or password." });
    //  }
    //  return done(null, user);
    }
  )
);


// ./mongoose/schames/user.mjs
import mongoose from "mongoose";

const userSchema = new mongoose.Schema({
  username:{
    type: mongoose.Schema.Types.String,
    required: true,
    unique: true,
    trim: true,
    minlength: 5,
    maxlength: 32
  },
  password: {
    type:mongoose.Schema.Types.String,
    required: true,
    trim: true,
    minlength: 8,
    maxlength: 128
  },
  age: mongoose.Schema.Types.Number,
  email: mongoose.Schema.Types.String,
  phone: mongoose.Schema.Types.String,
  address: mongoose.Schema.Types.String,
  createAt: {
    type: Date,
    default: Date.now
  }
});

export const User = mongoose.model("User", userSchema);

// ./utils/helper.mjs
import bcrypt from "bcrypt";

const saltRounds = 10;

export const hashPassword = async password => {
  const salt = await bcrypt.genSaltSync(saltRounds);
  const hash = await bcrypt.hashSync(password, salt);
  return hash;
};

export const comparePassword = async (password, hash) => {
  const result = await bcrypt.compareSync(password, hash);
  return result;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
上次更新: 3/13/2024