Comments (20)
Is it possible to disable index fallback to avoid this exception?
ServeStaticModule.forRoot({
rootPath: path.join(__dirname, '../../../public'),
serveStaticOptions: {
index: false,
},
}),
[2021-03-25T10:35:11.080] [INFO] NestApplication - Nest application successfully started
[2021-03-25T10:35:13.787] [ERROR] ExceptionsHandler - ENOENT: no such file or directory, stat '/Users/raphaelsoul/projects/zuma/nodejs/mock-server/public/index.html' Error: ENOENT: no such file or directory, stat '/Users/raphaelsoul/projects/zuma/nodejs/mock-server/public/index.html'
[2021-03-25T10:35:13.788] [ERROR] ExceptionsHandler - ENOENT: no such file or directory, stat '/Users/raphaelsoul/projects/zuma/nodejs/mock-server/public/index.html' Error: ENOENT: no such file or directory, stat '/Users/raphaelsoul/projects/zuma/nodejs/mock-server/public/index.html'
from serve-static.
serve-static/lib/loaders/express.loader.ts
Lines 44 to 59 in d0f4a89
res.sendFile
in renderFn
causes no such file
error.
I think it is the best practice. we dont need a global exeception filter
ServeStaticModule.forRoot({
rootPath: resolve(__dirname, '../public'),
serveRoot: '/',
}),
For SPAs it is never a problem cause you will always have an index.html
(or using index
specify a filename)
For serving static file in traditional frontend project, just give a non-empty serveRoot
.
Therefore, it seems there is no need for a PR to fix this, we just need update nestjs docs to declare usage for serving SPAs and non-SPAs
@kamilmysliwiec
UPDATE:
in some occasions, the solution above(give non empty serveRoot) still not works. For Example, you want to serve skins/material-design/assets
under /themes/material-design
.π
ServeStaticModule.forRoot({
rootPath: resolve(__dirname, '../skins/material-design/assets'),
serveRoot: '/themes/material-design',
})
code below does not throw exceptions to built-in ExceptionsHandler class
ServeStaticModule.forRoot({
rootPath: resolve(__dirname, '../skins/material-design/assets'),
serveRoot: '/themes/material-design/', // NOTE: it end with slash `/`
})
you can check the reason here(for express)
every request url start serveRoot
will be handled by express static middleware in line38 in the screenshot instead of renderFn
function
It is very tricky. Seems we need robust code in @nestjs/serve-static library
from serve-static.
@kamilmysliwiec Run into the same issue. Was able to catch the error and handle it appropriately here:
@Catch()
export class ServeStaticExceptionFilter implements ExceptionFilter {
catch( exception: any, host: ArgumentsHost ): any {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
if ( exception.code === "ENOENT" ) ) {
response.sendStatus( HttpStatus.NOT_FOUND );
}
response.sendStatus( status );
}
}
Main gotcha for me was the Catch decorator, since the error thrown is not an HttpException, be sure to leave catch everything.
from serve-static.
Just ran into the same issue. Even if an exception filter would be working, I think, a 404 would be the correct HTTP response code.
from serve-static.
@kamilmysliwiec @tristan957 here is a repo that reproduces the issue https://github.com/micaelmbagira/nestjs-service-static-139.
from serve-static.
It currently seems either impossible or not easily discoverable on how a developer can catch the serve-static 500 error and change it to a 404 for when a file is not found.
Have you tried creating a global exception filter?
from serve-static.
Yes. Sorry if that was not clear from the original issue. My exception filter aimed at catching these 500 errors in order to convert them to 404s.
The global exception filter does not get hit. I know this because my log statements did not come across the console. I can confirm that an instance of the exception filter was created, just not used. To create the global exception filter, I added a provider to my module using the documentation specified at docs.nestjs.com.
from serve-static.
Please, provide a minimal repository which reproduces your issue.
from serve-static.
I'll see about getting a reproducible repo tonight.
from serve-static.
@cyrilselasi have you found a good way to use the filter only on the route where you are serving static content?
from serve-static.
Not yet, I have it set as a global filter at the moment. That's working fine for my case
from serve-static.
Same issue here. Returning a 404 status code instead of catching the error 500 with a global exception filter is definitely the best option.
from serve-static.
PRs are more than welcome (if anyone is interested) :)
from serve-static.
@kamilmysliwiec I think maybe all I will try later today. Does not seem too hard to add at least (if I understand the code correctly) for the Express side of things which I use.
from serve-static.
index fallback
I have same issue
from serve-static.
Is it possible to disable index fallback to avoid this exception?
@raphaelsoul I don't think so due to the following:
serve-static/lib/loaders/abstract.loader.ts
Lines 13 to 15 in 72dc754
from serve-static.
A other use case I have have is serving a static SPA where we need to inject data into the index.html. It needs to be routed through a controller.
Currently i can have a controller that handles /index.html but /some-other-route would serve the index.html unparsed.
from serve-static.
It is possible to use async await in nestjs fastify to solve this problem
app.get(renderPath, async (req, res) => {
await new Promise((resolve, reject) => {
const stream = fs.createReadStream(indexFilePath);
stream.on("data", (chunk) => {
res.type('text/html').send(chunk);
resolve();
});
stream.on("error", () => {
reject(new NotFoundException()))
});
});
});
from serve-static.
I'm currently encountering a "404 File Not Found" error when using the HTTP custom exception filter. This poses an issue because we have static files. Ideally, we'd like to provide a more user-friendly experience than just a JSON response or header status code. Is there a way to implement a colorful custom 404 error page using static files in NestJS? I haven't been able to find a method within NestJS itself, so I resorted to serving static files through Nginx and configuring error handling there.
from serve-static.
@tuanpq1998 you can do something like this:
import { ArgumentsHost, Catch, ExceptionFilter } from "@nestjs/common";
import { NextFunction } from "express";
import path, { join } from "path";
import { fileURLToPath } from "url";
@Catch()
export class NotFoundExceptionFilter implements ExceptionFilter {
catch(exception : any, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const next = ctx.getNext<NextFunction>();
if ( exception.code === "ENOENT" ) {
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
response.sendFile(join(__dirname, '..', '..', 'public', '404_page.html'));
} else {
next(exception);
}
}
}
And then in your app.module.ts add the provider:
{
provide: APP_FILTER,
useClass: NotFoundExceptionFilter,
}
So something like:
providers: [
AppService,
{
provide: APP_FILTER,
useClass: NotFoundExceptionFilter,
}
],
This will serve /public/404_page.html when a file is not found.
from serve-static.
Related Issues (20)
- serveRoot doesn't work with fastify platform HOT 3
- Get dynamic path
- After updating static-asset to 3.x, excluded paths fallback to index.html ( instead of returning a 404 ) HOT 2
- path-style versioning of static asset HOT 1
- Serve static can't handle globalprefix HOT 1
- Nest can't resolve dependencies of the ServeStaticModule HOT 7
- Provide a documentation how to use setHeaders function
- Support `preCompressed` from `@fastify/static` HOT 1
- Cannot upgrade NestJS dependencies due to @fastify/static package HOT 1
- Not work if any controller in module has @Get('*') HOT 3
- Missing 'prefix' property in ServeStaticOptions HOT 1
- Action Required: Fix Renovate Configuration
- Error when set renderPath as regexp HOT 1
- serveStaticOptions: { index: false } doesn't work HOT 1
- Dependency Dashboard
- WatΡh changes in static folder and reload webpage on change (like browsersync) HOT 1
- Module '"@nestjs/serve-static"' has no exported member 'ServeStaticModule'. HOT 1
- fastify-static is deprecated use @fastify/static instead HOT 1
- Support for nestjs v9 HOT 1
- Transform/Manipulate index html before sending it HOT 6
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. πππ
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google β€οΈ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from serve-static.