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>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



猜您在找 对于错误“Refused to execute script from '...' because its MIME type ('') is not executable, and strict MIME type checking is enabled.”的处理。 [WEB]对于"Refused to execute script from 'http://xx.xx.xx/yy/zz.js' because its MIME type ('') is not executable, and strict MIME type checking is enabled."问题的解决办法 浏览器报错 Refused to apply style from 'http://******' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. HTML5 because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME c because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checkin "> js模版使用 控制台出现“The script has an unsupported MIME type ('text/html')”报错 html template & script type="text/html" script标签中type为"text/x-template"或"text/html" 是干什么的,为什么要把html写在js中? 这是什么编程语言风格,都能这样用吗?">