Import a Nest.js app as a simple Express middleware(将Nest.js应用程序作为简单的Express中间件导入)
本文介绍了将Nest.js应用程序作为简单的Express中间件导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Nestjs应用程序(睡觉API),我想将其作为简单的Express中间件(不是Nest中间件)导入到另一个节点模块中。实际上我还是不能使它工作。
// main.ts
// => The main file of my Nest app, this one is working properly.
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
// app.middleware.ts
import {Injectable, NestMiddleware} from '@nestjs/common';
import {NestFactory} from '@nestjs/core';
import {AppModule} from './app.module';
import {ExpressAdapter} from '@nestjs/platform-express';
import express, {Request, Response} from 'express';
const bootstrap = async () => {
const expressApp = express();
const adapter = new ExpressAdapter(expressApp);
const app = await NestFactory.create(AppModule, adapter);
await app.init();
return app;
};
@Injectable()
export class AppMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: Function) {
return bootstrap();
}
}
// express-app.ts
// => Here I'm trying to load my app through a simple Express middleware, but it doesn't works.
import express from 'express';
import { AppMiddleware } from './app.middleware';
const app = express();
const PORT = process.env.PORT || 3000;
app.use((req, res, next) => {
const app = new AppMiddleware().use(req, res, next);
app.then(next);
});
app.listen(PORT, () => {
console.log(`app running on port ${PORT}`);
});
从main.ts
运行我的应用程序时,它工作正常(所有路由都工作正常,我正在获取正确的数据)。但是,当我尝试通过express-app.ts
运行应用程序时,所有路由似乎都在工作(它们显示在终端中),但是在任何情况下,我都会收到以下错误,而不是返回JSON对象:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>[object Object]</pre>
</body>
</html>
嵌套组件版本:
- @nestjs/common: "^6.10.14"
- @nestjs/core: "^6.10.14"
- @nestjs/platform-express: "^6.10.14"
- express: "^4.16.4"
推荐答案
虽然我不允许将Nest用作中间件本身,但这是可能的。使用nest new express-server -p npm
中的基本设置创建新的NestJS应用程序,并使用src/server.ts
设置一个小型Express服务器,我能够运行以下代码。
app.midleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import { AppModule } from './app.module';
const bootstrap = async (express: Express.Application) => {
const app = await NestFactory.create(AppModule, new ExpressAdapter(express));
await app.init();
return app;
}
@Injectable()
export class AppMiddleware implements NestMiddleware {
constructor(private expressInstance: Express.Application) {}
use(req: any, res: any, next: () => void) {
console.log('In Nest middleware');
return bootstrap(this.expressInstance);
}
}
app.control er.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
app.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
app.module e.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
server.ts
import * as express from 'express';
import { AppMiddleware } from './app.middleware';
const app = express();
app.use((req, res, next) => {
const nest = new AppMiddleware(app).use(req, res, next);
nest.then(() => {
next();
}).catch(err => {
console.log(JSON.stringify(err));
next();
});
});
app.listen(3000, () => {
console.log('Listening on port 3000');
});
生成命令
npm run build
# mapped to nest build
启动命令
node dist/server.js
测试命令
▶ curl http://localhost:3000
Hello World!
控制台日志
Listening on port 3000
In Nest middleware
[Nest] 24235 - 02/18/2020, 8:05:44 PM [NestFactory] Starting Nest application...
[Nest] 24235 - 02/18/2020, 8:05:44 PM [InstanceLoader] AppModule dependencies initialized +15ms
[Nest] 24235 - 02/18/2020, 8:05:44 PM [RoutesResolver] AppController {
沃梦达教程
本文标题为:将Nest.js应用程序作为简单的Express中间件导入
基础教程推荐
猜你喜欢
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01