Refused to execute script from '....js' because its MIME type ('text/html') is not executable...

5 篇文章 0 订阅
1 篇文章 0 订阅

问题描述

在整合 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>
  • 19
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 14
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值