【发布时间】:2020-09-15 22:37:03
【问题描述】:
我收到以下错误:
Access to fetch at 'http://localhost:8080/users/find-all/0' from origin 'http://localhost:3000/' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
我知道有很多这类问题,但我就是无法解决问题。 后端使用 Spring Boot 构建,前端基于 ReactJS。
@GetMapping("/find-all/{page}")
public PaginatedResultDto<UserDto> findAllPaginated(@PathVariable("page") int page, @RequestParam(defaultValue = NUMBER_OF_ELEMENTS) int numberOfElements) {
Pageable pageable = PageRequest.of(page, numberOfElements);
return getBaseFacade().findAllPaginated(pageable);
}
还有
getPaginatedResults = (pageIndex, resultsPerPage, endpoint, jwt) => {
const resultsPerPagePath = resultsPerPage !== undefined ? "?numberOfElements=" + resultsPerPage : "";
const endpointPath = BASE_URL + "/" + endpoint + "/find-all/" + pageIndex + resultsPerPagePath;
return fetch(endpointPath, {
method: "GET",
headers: new Headers({
"Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Authorization",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
"Authorization": "Bearer " + jwt
})
}).then( .. some error handling here )
我是这样配置WebSecurityConfigurerAdapter的:
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/users/login").permitAll()
.antMatchers("/users/find-all/*").hasRole("ADMIN")
.anyRequest().authenticated()
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
我也有一个WebMvcConfigurer:
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*")
.allowedHeaders("Authorization", "Content-Type");
}
但我就是无法解决这个问题。我已经尝试了堆栈溢出的所有解决方案,但都没有奏效。
【问题讨论】:
-
不相关,但在 client 中设置 COR 标头完全没有意义。它说它没有得到一个 OK,检查你的请求和响应数据。
-
是这个资源服务器、授权服务器还是只是没有任何访问权限的服务器——意味着所有 api 都可以公开访问
-
@DaveNewton 我在浏览器控制台中登录时收到“TypeError:无法获取”响应。该请求正在与邮递员合作。
-
baeldung.com/spring-security-cors-preflight 您可能会在飞行前遇到身份验证错误。
-
@DaveNewton 非常感谢。这解决了我的问题 :) 祝你有美好的一天!
标签: java reactjs spring spring-boot cors