将 Express 应用程序迁移到 NestJS

2022-01-23 00:00:00 node.js migration express javascript nestjs

我有一个现有的 express 应用程序,它足够大.我想将它迁移到 NestJS 应用程序,但要逐步进行.所以我用现有的 Express 实例创建了 Nest 应用程序,但遇到了一个问题 - 所有嵌套处理程序总是在 Express 处理程序之后添加.但是我有一个根 Express 中间件,我只想将其应用于某些处理它的处理程序.如何在 Express 处理程序之前应用 Nest 处理程序?

I have an existing express application, and it is large enough. I want to migrate it to NestJS application, but do it step by step. So I have created Nest app with an existed Express instance, by faced a problem - all nest handlers always add after Express handlers. But I have a root Express middleware I want to apply only for some handlers that go after it. How can I apply Nest handlers before Express handlers?

例如.我创建了一个新的 NestJS 项目,并更改了 main.ts

For example. I created a new NestJS project, and changed main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ExpressAdapter } from '@nestjs/platform-express';
import * as express from 'express';

const expressApp = express();
const authMiddleware = (req, res) => res.end('Auth middleware');
expressApp.use(authMiddleware);
expressApp.get('/test', ((req, res) => res.end('Test')))

async function bootstrap() {
  const app = await NestFactory.create(AppModule, new ExpressAdapter(expressApp));

  await app.listen(3000);
}
bootstrap();

在根路径上,我希望看到 Hello World!,但我看到 Auth 中间件

On the root path I expect to see Hello World! but I see Auth middleware

我知道我可以做类似的事情

I understand that I can do something like

expressApp.get('/test', authMiddleware, ((req, res) => res.end('Test')))

但是当前的项目太大了,有子路由器,而不仅仅是一个中间件.也许还有另一种方法可以做到这一点?

But current project is too large with sub routers and not only one middleware. Maybe there is another way to do it right?

推荐答案

您的 auth 中间件总是结束请求,而不是像中间件通常那样行事.通常中间件有这样的签名......

Your auth middleware is always ending the request and not behaving the way middleware usually does. Typically middleware has a signature like this...

const authMiddleware = (req, res, next) => {
  // do auth things like verify a JWT and attach it to req.user

  next()
}
expressApp.use(authMiddleware)

const loggingMiddleware = (req, res, next) => {
  const { headers, body, user, route } = req
  console.log({ headers, body, user, route })
  next()
}
expressApp.use(loggingMiddleware)

在上面的代码中,authMiddleware 总是在 loggingMiddleware 之前执行,因为它是先附加的.例如,如果我们颠倒顺序并首先附加 loggingMiddleware,req.user 将始终未定义.Express 文档 对中间件控制流的运行方式和 NestJS 进行了非常详细的描述在引擎盖下遵循相同的模式.

In the above code, the authMiddleware ALWAYS executes before the loggingMiddleware because it was attached first. If, say, we reversed the order and attached loggingMiddleware first, req.user would always be undefined. The Express documentation is very descriptive in how the middleware control flow operates, and NestJS follows the same patterns under the hood.

相关文章