Service Worker registration error: Unsupported MIME type ('text/html')

  • 23,000
  • Tác giả: admin
  • Ngày đăng:
  • Lượt xem: 23
  • Tình trạng: Còn hàng

In my Express server application, I have one wildcard (asterisk / *) route that redirects to lớn index.html:

// Load React App
// Serve HTML tệp tin for production
if (env.name === "production") {
  ứng dụng.get("*", function response(req, res) {
    res.sendFile(path.join(__dirname, "public", "index.html"));
  });
}

This is a very common design pattern. However, it means that any requests for unknown text files initially get redirected to lớn 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 tệp tin.

The solution I found was to lớn 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"));
});

Now, when the browser looks for service-worker.js, Express will return it with the correct MIME type.

(Note that if you try adding the service-worker.js route after the wildcard, it won't work because the wildcard route will override.)