Node.js 面试避坑:Express 常见问题误区与正确答案解析

Express 作为 Node.js 的核心框架,面试中常因概念混淆或实践误区导致失分。以下是高频问题解析:


误区 1:中间件执行顺序无关紧要

❌ 错误认知
"中间件注册顺序不影响业务逻辑"
✅ 正确答案
中间件严格按注册顺序执行。例如认证中间件必须在路由前注册:

// 正确顺序
app.use(authentication); // 1. 先认证
app.use("/api", router); // 2. 后路由

// 错误顺序:未认证即可访问路由
app.use("/api", router); 
app.use(authentication); 


误区 2:app.use()app.get() 可互换

❌ 错误认知
"两者都是注册中间件,功能相同"
✅ 正确答案

  • app.use():处理所有HTTP方法(GET/POST等)
  • app.get():仅处理GET请求
// 正确场景
app.use("/static", express.static("public")); // 所有方法访问静态资源
app.get("/api/data", (req, res) => { ... });   // 仅响应GET请求


误区 3:忽略异步错误处理

❌ 错误认知
"try/catch 可捕获所有异步错误"
✅ 正确答案
Express 无法自动捕获异步错误,必须通过 next() 传递:

// 正确写法
app.get("/", async (req, res, next) => {
  try {
    await asyncOperation();
  } catch (err) {
    next(err); // 传递错误到集中处理中间件
  }
});

// 集中错误处理(需注册在最后)
app.use((err, req, res, next) => {
  res.status(500).json({ error: err.message });
});


误区 4:路由参数(:id)无需校验

❌ 错误认知
":id 天然是合法ID,无需验证"
✅ 正确答案
必须验证参数格式,防止非法注入:

// 正确做法:添加校验中间件
app.param("id", (req, res, next, id) => {
  if (!/^\d+$/.test(id)) {
    return res.status(400).send("Invalid ID");
  }
  next();
});

app.get("/user/:id", (req, res) => {
  // 安全使用 req.params.id
});


误区 5:res.send() 自动设置 Content-Type

❌ 错误认知
"任何数据调用 res.send() 都会自动设置正确的头部"
✅ 正确答案

  • 字符串:默认为 text/html
  • 对象/数组:默认为 application/json
    需显式指定类型
// 返回XML需手动设置
res.type("application/xml");
res.send("<data><value>1</value></data>");


避坑总结
  1. 中间件顺序:按依赖关系严格排序
  2. 路由方法:区分 app.use(全方法)和 app.get(单方法)
  3. 错误处理:异步操作必须 next(err)
  4. 参数安全:路由参数强制校验格式
  5. 响应头部:非JSON数据显式指定 Content-Type

掌握这些核心点,可规避 80% 的 Express 面试陷阱。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐