Skip to content

Commit

Permalink
feat:Jump to the related 404 page file for the local server when runn…
Browse files Browse the repository at this point in the history
…ing (#4719)

Now in our current server.js, when the route is invalid, only "Not Found" is returned. Actually to mock what we see from the official site, it seems we should return you a 404 page instead.
  • Loading branch information
SEWeiTung authored Jul 26, 2022
1 parent f0c00db commit 6fc849b
Showing 1 changed file with 38 additions and 1 deletion.
39 changes: 38 additions & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ staticFiles.on('add', (filePath) => {
});

const mainLocale = (selectedLocales && selectedLocales[0]) || 'en';
let all404NotFoundPageContent = null;

// Initializes the server and mounts it in the generated build directory.
http
Expand All @@ -120,7 +121,43 @@ http
if (req.url === '/') {
req.url = `/${mainLocale}`;
}
mount(req, res);

mount(req, res, async () => {
// Here we should handle the 404 page when the route is not found.
// 1. Check whether the language is supported or not.
// 2. If not, redirect to the default language.
// 3. If yes, Save the content and return directly for the next time.

if (all404NotFoundPageContent === null) {
const allSupportedLangs = await fs.readdir(
path.join(__dirname, 'locale')
);
all404NotFoundPageContent = new Map();
for (const lng of allSupportedLangs) {
all404NotFoundPageContent.set(lng, '');
}
}

let currentLng = req.url.split('/')[1];

if (!all404NotFoundPageContent.has(currentLng)) {
currentLng = mainLocale;
}

if (all404NotFoundPageContent.get(currentLng) === '') {
const notFoundPagePath = path.join(
__dirname,
'build',
`${currentLng}/404.html`
);
all404NotFoundPageContent.set(
currentLng,
await fs.readFile(notFoundPagePath, 'utf8')
);
}

res.end(all404NotFoundPageContent.get(currentLng));
});
})
.listen(port, () => {
console.log(
Expand Down

0 comments on commit 6fc849b

Please # to comment.