Refused to execute script from '....js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.md

问题描述

在整合 Spring Boot、Spring Security、Thymeleaf 的练习中,对页面进行调试时,发现如下错误提示:
Refused to execute script from 'http://localhost:8080/codelib-springsecurity-sample-web/js/ie10-viewport-bug-workaround.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

调试图

解决过程

1、 首先看到 “because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled”,因为 Thymeleaf 对于页面的元素必须是严格的格式,所以我以为是因为我页面代码上没有加 type="text/javascript" 的原因。

<script th:src="@{js/ie-emulation-modes-warning.js}" src="../static/js/ie-emulation-modes-warning.js" type="text/javascript"></script>

结果加上了并不能解决问题。

2、 再看 “Refused to execute script ...”,为什么会被拒绝执行呢?进而想到可能是权限的控制问题,亦即是 Spring Security 的静态资源访问配置问题。经核查,的确是这样的问题。
正确配置如下:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        // http.authorizeRequests()每个匹配器按照它们被声明的顺序被考虑。
        http
            .authorizeRequests()
                // 所有用户均可访问的资源
                .antMatchers("/css/**", "/js/**","/images/**", "/webjars/**", "**/favicon.ico", "/index").permitAll()
                // ROLE_USER的权限才能访问的资源
                .antMatchers("/user/**").hasRole("USER")
                // 任何尚未匹配的URL只需要验证用户即可访问
                .anyRequest().authenticated()
                .and()
            .formLogin()
                // 指定登录页面,授予所有用户访问登录页面
                .loginPage("/login")
                .permitAll()
                .and()
            .headers()
                .frameOptions().sameOrigin(); 
    }

问题在于我原来配置中没有将 "/js/**" 的路径添加到配置中,导致没有验证的用户没有权限访问。

总结

项目结构如下,假如我要能否访问 plugins 文件夹下的文件,也需要将 “/plugins/**” 添加到相应到上述的配置中,允许所有请求访问。
项目结构图

注:对于Spring Boot 整合 Thymeleaf,静态资源默认存放在 static 文件夹下,在页面上写路径上不需要加上 static 路径,而 html 页面则放在 templates 文件夹下。

所以写法如下:

<script th:src="@{js/ie-emulation-modes-warning.js}" src="../static/js/ie-emulation-modes-warning.js" type="text/javascript"></script>
原文地址:https://www.cnblogs.com/zhanyao/p/7351730.html