更新时间:2022-03-23 03:03:52
在我的 Express 服务器应用程序中,我有一个通配符(星号/*)路由重定向到 index.html
:
In my Express server application, I have one wildcard (asterisk / *) route that redirects to index.html
:
// Load React App
// Serve HTML file for production
if (env.name === "production") {
app.get("*", function response(req, res) {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
}
这是一种非常常见的设计模式.然而,这意味着对未知文本文件的任何请求最初都会被重定向到 index.html
,因此返回的 MIME 类型为 "text/html"
,即使它是实际上是 JavaScript 或 SVG 或其他类型的纯文本文件.
This is a very common design pattern. However, it means that any requests for unknown text files initially get redirected to index.html
, and therefore return with the MIME type of "text/html"
, even if it's actually a JavaScript or SVG or some other kind of plaintext file.
我找到的解决方案是为 service-worker.js
before 通配符路由添加一个特定的路由:
The solution I found was to add a specific route for service-worker.js
before the wildcard route:
app.get("/service-worker.js", (req, res) => {
res.sendFile(path.resolve(__dirname, "public", "service-worker.js"));
});
app.get("*", function response(req, res) {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
现在,当浏览器查找 service-worker.js
时,Express 将返回它并带有正确的 MIME 类型.
Now, when the browser looks for service-worker.js
, Express will return it with the correct MIME type.
(请注意,如果您尝试在通配符后添加 service-worker.js
路由,它将不起作用,因为通配符路由将覆盖.)
(Note that if you try adding the service-worker.js
route after the wildcard, it won't work because the wildcard route will override.)