将Express应用程序迁移到NestJS [英] Migrating Express application to NestJS

查看:50
本文介绍了将Express应用程序迁移到NestJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的快速申请,而且足够大.我想将其迁移到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?

推荐答案

您的身份验证中间件始终会终止请求,并且行为不正常.通常,中间件具有这样的签名...

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.

这篇关于将Express应用程序迁移到NestJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆