添加删除端点时,由于Spring MVC中的MIME类型,java资源被阻止
我正在使用SpringBootV2开发一个web应用程序。1.9.释放并释放胸腺素。该应用程序混合了服务器端渲染(SpringMVC常规控制器)和通过AJAX调用的rest控制器。只要GET
和POST
是我唯一使用的HTTP方法,这个页面就很有魅力。当我添加一个完全不相关但未使用的REST控制器时,CSS和JS资源将停止加载,浏览器控制台中将显示如下错误:
The resource from “http://localhost:8080/css/demo.css” was blocked due to MIME type (“application/json”) mismatch (X-Content-Type-Options: nosniff)
如果我移除新控制器,页面将再次开始工作
当我使用网络监视器检查请求时,我观察到:
X-Content-Type-Options: nosniff
头始终存在于响应中,这与Spring Security documentation一致李>- 如果
DELETE
端点不在那里,则GET /css/demo.css
请求返回HTTP 200
代码,这与预期的一致。Accept
(请求头)和Content-Type
(响应头)都标记为text/css
李> - 当我添加端点时,上面的请求返回一个
HTTP 405
Accept
头是text/css
,但Content-Type
变成了application/json
。此外,还添加了一个新的响应头:Allow: DELETE
李>
我的猜测是,当Spring扫描控制器并找到DELETE
方法时,会自动添加一些额外的配置,但我找不到任何参考来确认这一点。我想知道为什么会发生这种情况,以及如何避免这种行为
因为我正在开发本地,所以我的Spring安全配置非常简单:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public AuthenticationManagerConfigurer authConfigurer() {
return new InMemoryAuthenticationManagerConfigurer();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
authConfigurer().configure(auth);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
我添加的REST控制器几乎不起任何作用:
@RestController
public class MotivosController {
private final String CONTROLLER_PATH = "/rest/motivos/{id}";
@RequestMapping(name=CONTROLLER_PATH, method=RequestMethod.DELETE)
public void deleteMotivo(@PathVariable(name="id") String id) {
logger.debug("Eliminando el motivo " + id);
}
// Other members I consider unrelated to the problem go here...
}
CSS和JS文件正在加载到template.html
文件夹下的src/main/resources/templates
文件中,如下所示:
<link type="text/css" href="/css/demo.css" rel="stylesheet" />
# 1 楼答案
答案比我想象的要简单,我的假设完全错了。我混淆了
@RequestMapping
的name
属性和value
属性,因此任何URL都与该方法匹配。将name
更改为value
使其工作