FastAPI 静态文件 MIME 类型返回错误导致 ESM 报错 Strict MIME type checking?

作者站长头像
站长
· 阅读数 15

同样一个Web应用。家里使用正常。复制到公司电脑启动后访问就报错。

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec.

Chrome/Firefox都这样。

用fastapi写的。代码文件都是复制过去的。

app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/main/assets", StaticFiles(directory="static/assets"), name="static")

@app.get("/")
async def redirect_to_static():
    return RedirectResponse(url="/main")


@app.get("/main", response_class=HTMLResponse)
async def static_endpoint(request: Request):
    return templates.TemplateResponse("static/index.html", {"request": request})

import uvicorn

if __name__ == '__main__':
    file = Path(__file__)
    uvicorn.run(app=f'{file.stem}:app', host="127.0.0.1", port=8000, reload=True)
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <link rel="icon" href="/static/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vite App</title>
    <script type="module" crossorigin src="/static/assets/index-DIiKvbdV.js"></script>
    <link rel="stylesheet" crossorigin href="/static/assets/index-CMasdhyl.css">
  </head>
  <body>
    <div id="app"></div>

  </body>
</html>

FastAPI 静态文件 MIME 类型返回错误导致 ESM 报错 Strict MIME type checking?

FastAPI 静态文件 MIME 类型返回错误导致 ESM 报错 Strict MIME type checking?

回复
1个回答
avatar
test
2024-06-20

类似问题: https://github.com/pallets/flask/issues/1045

虽然👆这个是 Flask 不是 FastAPI,但原因都一样,就是 Windows 注册表因为未知原因损坏导致 MIME 类型映射有问题。

具体解决方案见评论区。

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容