I have a NestJs and Angular app. It took some time to get a "production" version running and I was able to eventually figure it out using a setup like so in my main.ts server file:
app.use('*', (req, res) => {
res.sendFile(CLIENT_FILES + '/index.html');
});
In now trying to move to an implemented middleware:
I've been working off of Bo's example here to implement middleware: https://medium.com/@bo.vandersteene/use-nest-as-your-server-side-application-with-an-angular-frontend-540b0365bfa3
My middleware is getting hit for every request but I cannot get any information from the Request parameter so nothing is taking place and the app itself hangs. I'm not sure what step I missed or if I have an existing setup that is preventing visibility into the request object. Any direction is much appreciated
Below are my logs from the middleware:
Results
da req get path : /
da req get originalUrl : /
da req get hostname : localhost
da req get baseUrl :
da req get url: /
my frontendmiddleware.ts:
import { NestMiddleware, Injectable } from "@nestjs/common";
import { join } from 'path';
import { Request, Response } from 'express';
const allowedExt = [
'.js',
'.ico',
'.css',
'.png',
'.jpg',
'.woff2',
'.woff',
'.ttf',
'.svg',
];
const ROUTE_PREFIX = 'api';
const resolvePath = (file: string) => join(__dirname, '..', file);
@Injectable()
export class FrontendMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: Function) {
console.log('da req : ' + req );
console.log( ' da req get path : ' + req.path);
console.log( ' da req get originalUrl : ' + req.originalUrl);
console.log( ' da req get hostname : ' + req.hostname);
console.log( ' da req get baseUrl : ' + req.baseUrl);
console.log( ' da req get url: ' + req.url );
const { url } = req;
if (url.indexOf(ROUTE_PREFIX) === 1) {
// it starts with /api --> continue with execution
next();
} else if (allowedExt.filter(ext => url.indexOf(ext) > 0).length > 0) {
// it has a file extension --> resolve the filea
console.log('here be the other files: ' + resolvePath(url));
res.sendFile(resolvePath(url));
} else {
// in all other cases, redirect to the index.html!
res.sendFile(resolvePath('index.html'));
}
}
}
my app.module.ts
import { Module, NestModule, RequestMethod, MiddlewareConsumer } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { SharedModule } from './shared/shared.module';
import { ConfigurationService } from './shared/configuration/configuration.service';
import { Configuration } from './shared/configuration/configuration.enum';
import { UserModule } from './user/user.module';
import { FrontendMiddleware } from './middleware/frontend.middleware';
@Module({
imports: [
SharedModule,
MongooseModule.forRoot(ConfigurationService.connectionString),
UserModule
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule {
constructor(private readonly configurationService: ConfigurationService) {
AppModule.port = AppModule.normalizePort(configurationService.get(Configuration.PORT));
AppModule.host = configurationService.get(Configuration.HOST);
AppModule.isDev = configurationService.isDevelopment;
console.log('port : ' + AppModule.port);
console.log('host : ' + AppModule.host);
console.log('isDev : ' + AppModule.isDev);
}
configure(consumer: MiddlewareConsumer): void {
consumer.apply(FrontendMiddleware).forRoutes(
{
path: '/**', // For all routes
method: RequestMethod.ALL, // For all methods
},
);
}
static host: string;
static port: number | string;
static isDev: boolean;
private static normalizePort(param: number | string): number | string {
const portNumber: number = typeof param === 'string' ? parseInt(param, 10) : param;
if (isNaN(portNumber)) {
return param;
} else if (portNumber >= 0) {
return portNumber;
}
}
}
my new main.ts:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './shared/filters/http-exception.filter';
import { join } from 'path';
declare const module: any;
async function bootstrap() {
const app = await NestFactory.create(AppModule);
if (module.hot) {
module.hot.accept();
module.hot.display(() => app.close());
}
app.useGlobalFilters(new HttpExceptionFilter());
app.enableCors();
await app.listen(AppModule.port);
}
bootstrap();
UPDATE -- in workign through the documentation, i was able to get the "functional middleware" working but still no luck with the middleware class ( https://docs.nestjs.com/middleware)
export function logger(req, res, next) {
console.log(`Request...`);
next();
};