Skip to content

Commit 6fc849b

Browse files
authored
feat:Jump to the related 404 page file for the local server when running (#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.
1 parent f0c00db commit 6fc849b

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

server.js

+38-1
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ staticFiles.on('add', (filePath) => {
110110
});
111111

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

114115
// Initializes the server and mounts it in the generated build directory.
115116
http
@@ -120,7 +121,43 @@ http
120121
if (req.url === '/') {
121122
req.url = `/${mainLocale}`;
122123
}
123-
mount(req, res);
124+
125+
mount(req, res, async () => {
126+
// Here we should handle the 404 page when the route is not found.
127+
// 1. Check whether the language is supported or not.
128+
// 2. If not, redirect to the default language.
129+
// 3. If yes, Save the content and return directly for the next time.
130+
131+
if (all404NotFoundPageContent === null) {
132+
const allSupportedLangs = await fs.readdir(
133+
path.join(__dirname, 'locale')
134+
);
135+
all404NotFoundPageContent = new Map();
136+
for (const lng of allSupportedLangs) {
137+
all404NotFoundPageContent.set(lng, '');
138+
}
139+
}
140+
141+
let currentLng = req.url.split('/')[1];
142+
143+
if (!all404NotFoundPageContent.has(currentLng)) {
144+
currentLng = mainLocale;
145+
}
146+
147+
if (all404NotFoundPageContent.get(currentLng) === '') {
148+
const notFoundPagePath = path.join(
149+
__dirname,
150+
'build',
151+
`${currentLng}/404.html`
152+
);
153+
all404NotFoundPageContent.set(
154+
currentLng,
155+
await fs.readFile(notFoundPagePath, 'utf8')
156+
);
157+
}
158+
159+
res.end(all404NotFoundPageContent.get(currentLng));
160+
});
124161
})
125162
.listen(port, () => {
126163
console.log(

0 commit comments

Comments
 (0)