angular - Nginx:带有 Web 组件的 Angular 应用程序 - 脚本类型 ="module"错误

标签 angular nginx ecmascript-6 server

我想使用简单的 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.

我找到了几个解决方案(例如 thisthat)建议我应该手动配置所有 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/

相关文章:

javascript - Visual Studio 无法识别 ES6 模板字符串

javascript - Angular Forms 不从 HTML 传递数据

javascript - 根据对象数组生成树

angular - 在 Ionic 2 中显示后退按钮和右侧菜单

ruby-on-rails - 在远程 SSL 代理后面使用 Rails config.force_ssl 进行无限重定向

nginx - 禁止访问 Monterey 上的/Users/user/中的文件夹

javascript - *.default 不是构造函数,带有导入的js插件

javascript - 带有自定义颜色管道的 AG-Grid

logging - 是否可以在 Nginx 上指定自定义错误日志格式?

javascript - 如何在辅助函数中使用箭头函数代替 'bind'