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

目录javascript

问题描述

在整合 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.css

调试图

解决过程

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

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

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

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

@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/**" 的路径添加到配置中,致使没有验证的用户没有权限访问。spring

总结

项目结构以下,假如我要可否访问 plugins 文件夹下的文件,也须要将 “/plugins/**” 添加到相应到上述的配置中,容许全部请求访问。
项目结构图ide

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

因此写法以下:code

<script th:src="@{js/ie-emulation-modes-warning.js}" src="../static/js/ie-emulation-modes-warning.js" type="text/javascript"></script>
相关文章
相关标签/搜索