I've a Nestjs app (a Rest API) that I would like to import in another node module, as a simple Express middleware (not a Nest middleware). Actually I'm still not able to make it working.
// 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}`);
});
When running my app from main.ts
it's working properly (all the routes are working and I'm getting the correct data). However when I try to run the app through express-app.ts
, all the routes seems working (they are displayed in the terminal), but instead of returning a JSON object, in any case I'm getting this error:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>[object Object]</pre>
</body>
</html>
Nest component versions:
- @nestjs/common: "^6.10.14"
- @nestjs/core: "^6.10.14"
- @nestjs/platform-express: "^6.10.14"
- express: "^4.16.4"