I am making Angular + NestJS app, and I want to send index.html
file for all routes.
main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useStaticAssets(join(__dirname, '..', 'frontend', 'dist', 'my-app'));
app.setBaseViewsDir(join(__dirname, '..', 'frontend', 'dist', 'my-app'));
await app.listen(port);
}
app.controller.ts
@Controller('*')
export class AppController {
@Get()
@Render('index.html')
root() {
return {};
}
}
It works fine while I open localhost:3000/
, but if I open localhost:3000/some_route
the server falls with 500 internal error
and says Can not find html module
.
I was searching why I am getting this error and everyone says set default view engine like ejs or pug
, but I don't want to use some engines, I just want to send plain html built by angular without hacking like res.sendFile('path_to_file')
. Please help
You can only use
setBaseViewsDir
and@Render()
with a view engine like handlebars (hbs); for serving static files (Angular), however, you can only useuseStaticAssets
andresponse.sendFile
.To serve
index.html
from all other routes you have a couple of possibilities:A) Middleware
You can create a middleware that does the redirect, see this article:
and then register the middleware for all routes:
B) Global Error Filter
You can redirect all
NotFoundExceptions
to yourindex.html
:and then register it as a global filter in your
main.ts
: