53

After deploying an Angular app on Heroku, a blank page is shown when URL is reached and console is showing MIME type errors.

error is:

Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

13 Answers 13

51

One possible explanation for the error:
You get this behavior when you deploy your app into a subfolder, not directly on your base-URL.

What happens:

  • The HTML is found when you go to www.yourbase.com/yoursubfolder/index.html, but the angular app fetches resources with relative path (let's say resource.css) from www.yourbase.com/resource.css instead of from www.yourbase.com/yoursubfolder/resource.css
  • your webserver probably serves some default page onwww.yourbase.com/resource.css (maybe your www.yourbase.com/index.html)
  • So the content of that default page is loaded instead of your CSS.

To fix it

Build your angular app with

ng build --prod --base-href yoursubfolder

Or set the base path in your index.html

<head>
    <base href="/yoursubfolder/">
</head>
Sign up to request clarification or add additional context in comments.

2 Comments

If, like me, you cannot rebuild your site, you can open the index.html file in your root folder and fix your base path in the <base> tag inside <head>
For me it only worked with surrounding slashed: ng build --base-href /yoursubfolder/
19

I got the same error when I try to deploy angular UI in a subfolder of nginx.

Finally, I fixed it. Wish it helpful.

Let's say if you want to host your website https://www.yourdomain.com/sub1/

Step 1: use --base-href to build

ng build --base-href=/sub1/

Step 2: config in nginx

There are 2 ways to host your subfolder.

Assuming that your dist folder locates in html/sub1dist

1)Host local dist as subfolder

server {
    listen       80;
    server_name  localhost;


    location /sub1 {
        alias   html/sub1dist;
        try_files $uri $uri/ /index.html =404;
    }
}

2)Proxy pass another endpoint as subfolder

server {
    listen       80;
    server_name  localhost;

    location /sub1/ {
        # rewrite to remove the subfolder
        rewrite ^/sub1/(.*)$ /$1 break;
        proxy_pass http://127.0.0.1:8071;
    }
}

server {
    listen       8071;
    server_name  localhost;

    location / {
        root   html/sub1dist;
        try_files $uri $uri/ /index.html =404;
    }
}

Each of above solutions works fine for me.

2 Comments

Thank you so much. I was going crazy due to this issue..
Wow... The fact that alias /html/sub1dist or alias /sub1dist (while having a root html) do not work, was about to make my head explode... Thank you so much!
9

I had the same error. The culprit was in my express server.js file.

app.use(express.static(__dirname + '/dist/<app-folder-name>'));

// PathLocationStrategy
app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname + '/dist/<app-folder-name>/index.html'));
})

If you don't include your app-folder-name after the dist folder for the express.static method it will result in the MIME type error since it can't locate your Javascript bundles.

Comments

3

Please try this, it worked for me

"server": {
      "builder": "@angular-devkit/build-angular:server",
      "options": {
        "outputPath": "dist/server",

Change like below:

"outputPath": "dist/",

Comments

2

You should look into using the X-Content-Type-Options header with the 'nosniff' property on your server.

Essentially, MIME is in place to allow the browser to automatically detect if the content-type being sent is correct for the application. Using the above header and property essentially tells the server - 'I got this'. In turn it should stop the MIME errors.

You can check the mozilla docs on X-Content-Type-Options here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options

Comments

2

it works for me when use angular8 with express:

app.use('/', express.static('classvideo'));

app.get('*', (req,res,next) => {
    const indexFile = path.resolve(__dirname + '/classvideo/index.html');
    res.sendFile(indexFile);
});

Comments

2

If using DotNetCore 3.1 make sure app.UseSpaStaticFiles(); is in Startup.cs.

Comments

2

Make sure to deploy the same build in the servers of load balancing.

There is one possibility that you are using load balancing in deployment and you just update the deployment in one server. Therefore, there are two versions in the deployment.

Due to the loading balancing, the browser resolves the files path in the index.html to different servers with different versions of files. In this case, the missing file points to the index.html itself. That is why you see the issue of loading module.

Comments

1

In my case, I had the same problem publishing an Angular 9 application on an IIS 8 server. The error only occurred on the customer's machine and not on mine. The reason was this: In my machine I published the application indicating in the baseRef that it would be inside a folder myFolder within the Site. In the case of my customer, he did not create the folder within an existing site, but instead created the folder and a new site that points directly to it. The solution in my case was to generate the publish without specifying the baseRef (just ng build --prod).

In short, the error is that the server cannot locate the project files according to how it was compiled.

Comments

0

In my case it was the issue from the server side. Rewriting handled it perfectly. Adding the below code in .htaccess worked perfectly.

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

    # Don't rewrite files or directories
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]

    # Rewrite everything else to index.html
    # to allow html5 state links
    RewriteRule ^ index.html [L]
</IfModule>

Comments

0

For me I just had to clear the browser cache and site starts loading.

Comments

0

I also had the similar problem. When I was trying to deploy to render.com

It could be because the path is not resolved correctly. Please refer below code for solution.

// serve static assets in production
if (process.env.NODE_ENV === 'production') {
  const staticPath = path.resolve(__dirname, '../../', 'client', 'dist');
  // set a static folder
  app.use(express.static(staticPath));

  // serve index.html
  app.get('*', (req, res) => {
    res.sendFile(path.resolve(staticPath, 'index.html'));
  });
}

Comments

0

I faced this issue with Angular 15 and a deployment on Azure app service.

This error typically occurs when the server is serving JavaScript files with an incorrect MIME type.

To fix this issue, you need to configure the MIME types in your (Azure) deployment.

  1. Create a web.config file if it doesn't already exist in the root of your Angular application. This file will be used to configure your Azure deployment settings.
  2. Add the following XML content to the web.config file:
<?xml version="1.0"?>
<configuration>
    <system.webServer>
        <staticContent>
            <clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
            <remove fileExtension=".json" />
            <remove fileExtension=".woff" />
            <remove fileExtension=".woff2" />
            <remove fileExtension=".js" />
            <mimeMap fileExtension=".json" mimeType="application/json" />
            <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
            <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
            <mimeMap fileExtension=".js" mimeType="application/javascript" />
        </staticContent>
        <rewrite>
            <rules>
                <rule name="Angular4" stopProcessing="true">
                    <match url=".*" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="/" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

This configuration will ensure that the specified file extensions are served with the correct MIME types.

  1. Save the web.config file and redeploy your Angular app to Azure.

If you still encounter the issue, make sure to clear your browser cache before testing again, as your browser may have cached the incorrect MIME type.

Kindly note that you only need the following to resolve this error:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <remove fileExtension=".js" />
      <mimeMap fileExtension=".js" mimeType="application/javascript" />
    </staticContent>
  </system.webServer>
</configuration>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.