fix: astro preview does not serve custom 404 (4113) (#4189)
* fix: astro preview does not serve custom 404 (4113) * fix: use exists instead of stat * Create thick-ducks-sparkle.md Co-authored-by: Nate Moore <natemoo-re@users.noreply.github.com>
This commit is contained in:
parent
ad3d786e1f
commit
5e71a8720e
2 changed files with 18 additions and 1 deletions
5
.changeset/thick-ducks-sparkle.md
Normal file
5
.changeset/thick-ducks-sparkle.md
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
---
|
||||||
|
"astro": patch
|
||||||
|
---
|
||||||
|
|
||||||
|
Fix custom 404 pages when using `astro preview` (#4113)
|
|
@ -3,6 +3,7 @@ import type { AddressInfo } from 'net';
|
||||||
import type { AstroConfig } from '../../@types/astro';
|
import type { AstroConfig } from '../../@types/astro';
|
||||||
import type { LogOptions } from '../logger/core';
|
import type { LogOptions } from '../logger/core';
|
||||||
|
|
||||||
|
import fs from 'fs';
|
||||||
import http from 'http';
|
import http from 'http';
|
||||||
import { performance } from 'perf_hooks';
|
import { performance } from 'perf_hooks';
|
||||||
import sirv from 'sirv';
|
import sirv from 'sirv';
|
||||||
|
@ -77,7 +78,18 @@ export default async function preview(
|
||||||
default: {
|
default: {
|
||||||
// HACK: rewrite req.url so that sirv finds the file
|
// HACK: rewrite req.url so that sirv finds the file
|
||||||
req.url = '/' + req.url?.replace(baseURL.pathname, '');
|
req.url = '/' + req.url?.replace(baseURL.pathname, '');
|
||||||
staticFileServer(req, res, () => sendError('Not Found'));
|
staticFileServer(req, res, () => {
|
||||||
|
const errorPagePath = fileURLToPath(config.outDir + '/404.html');
|
||||||
|
if (fs.existsSync(errorPagePath)) {
|
||||||
|
res.statusCode = 404;
|
||||||
|
res.setHeader('Content-Type', 'text/html;charset=utf-8');
|
||||||
|
res.end(fs.readFileSync(errorPagePath));
|
||||||
|
} else {
|
||||||
|
staticFileServer(req, res, () => {
|
||||||
|
sendError('Not Found');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue