【问题标题】:Nginx does not want to give me the .tsx file as an application/x-javascript, instead he gives application/octet-streamNginx 不想将 .tsx 文件作为 application/x-javascript 提供给我,而是提供 application/octet-stream
【发布时间】:2023-02-05 22:59:14
【问题描述】:

我有一个通过 Vite 构建的 dockerized React 应用程序。我希望我可以在自己独立的开发域中开发它。但显然 Nginx 不允许我这样做。我的 main.tsx 文件出现错误“无法加载模块脚本:需要一个 JavaScript 模块脚本,但服务器以“application/octet-stream”的 MIME 类型响应。对模块强制执行严格的 MIME 类型检查每个 HTML 规范的脚本。”

nginx 反向代理配置

server {
    # Listen to port 443 on both IPv4 and IPv6.
    listen 443 ssl;
    listen [::]:443 ssl; 

    server_name example.com;

    # Load the certificate files.
    ssl_certificate         /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key     /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;

    # Load the Diffie-Hellman parameter.
    ssl_dhparam /etc/letsencrypt/dhparams/dhparam.pem;

    proxy_http_version 1.1;

    location / {
        resolver 127.0.0.11;
        set $upstream http://example_front-app:80;
        # nginx will now start if host is not reachable
        proxy_pass    $upstream;
        proxy_set_header Host            $host;
        proxy_set_header X-Forwarded-For $remote_addr;
    }
}

容器内的nginx配置

server {
    listen 80;
    server_name example.com;

    root /var/www;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ =404;
    }
    
    
}

请不要建议我将文件编译成js扩展并以这种方式输出,我知道它有效。但我需要使用 ESNext 进行热开发

【问题讨论】:

标签: reactjs nginx vite nginx-reverse-proxy tsx


【解决方案1】:

您可以在 /etc/nginx/mime.types 的 nginx 配置中为 tsx 文件添加 mime 类型。

# /etc/nginx/mime.types

types {
        ...
    application/javascript                           js;
    application/javascript                           tsx;
        ...
}

通过使用位置指令

location ~* .tsx$ {
    types { } default_type "application/javascript; charset=utf-8";

    ...
}

检查nginx配置是否OK

nginx -t
nginx -s reload

希望这可以帮助。

【讨论】:

  • location ~* .tsx$ { 为这些文件创建一个位置后缀块(通常在 nginx 中效率低下)的原因是什么?
猜你喜欢
  • 2023-03-08
  • 2013-04-12
  • 1970-01-01
  • 2019-11-14
  • 1970-01-01
  • 2023-03-22
  • 2016-10-15
相关资源
最近更新 更多