同样一个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>
类似问题: https://github.com/pallets/flask/issues/1045
虽然👆这个是 Flask 不是 FastAPI,但原因都一样,就是 Windows 注册表因为未知原因损坏导致 MIME 类型映射有问题。
具体解决方案见评论区。