且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

服务人员注册错误:不支持的MIME类型('text / html')

更新时间:2022-03-23 03:04:10

在我的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 之前通配符路由:

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.)