我想使用简单的 Nginx 服务器为 Angular 8 应用程序提供服务。不幸的是,当我尝试提供该应用程序时,我在 Chrome 中收到以下错误:
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec.
我找到了几个解决方案(例如 this 和 that)建议我应该手动配置所有 script
标签并添加 type="javascript"
。但是,在我的情况下,我不能这样做,因为我的应用程序包含只能在脚本类型属性为 type="module"
时加载的 Web 组件。
我的 Nginx 配置如下所示:
events { worker_connections 1024; }
http
{
sendfile on;
server {
root /usr/share/nginx/html/app;
listen 9020;
server_name localhost;
location / {
index index.html index.htm;
}
location ~ \.css {
add_header Content-Type text/css;
}
location ~ \.js {
add_header Content-Type application/javascript;
}
}
}
你知道我如何配置 Angular 或 Nginx 来提供“模块”类型的 javascript 文件(包含在 index.html
中的 script
标签中)吗?
提前谢谢你。
最佳答案
您应该提供具有 type="module"
和 mime 类型 text/javascript
的 javascript,如 here 所述:
.js files need to be loaded with a MIME-type of text/javascript (or another JavaScript-compatible MIME-type, but text/javascript is recommended), otherwise you'll get a strict MIME type checking error like "The server responded with a non-JavaScript MIME type".
除此之外,您的 nginx SPA 配置不正确,因为它从未到达 .js 位置语句。您应该添加一个 try_files
语句:
server {
root /usr/share/nginx/html/app;
listen 9020;
server_name localhost;
location / {
try_files $uri $uri/ /index.html;
}
location ~* ^.+\.css$ {
default_type text/css;
}
location ~* ^.+\.js$ {
default_type text/javascript;
}
}
关于angular - Nginx:带有 Web 组件的 Angular 应用程序 - 脚本类型 ="module"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60171575/