Ron*_*zen 7 cors spring-boot angular
我为所有来源和标题启用了 cors,但是当我get从我的 angular 应用程序调用一个方法到 spring boot时,我仍然收到 cors 错误。
来自控制台的 Cors 错误:
Access to XMLHttpRequest at 'http://localhost:8080/api/users/test@ronny.nl' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)
我的controller(我打电话给 getbyemail):
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping(value = "/api/users", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserController {
private final UserService userService;
@Autowired
public UserController(final UserService userService) {
this.userService = userService;
}
@GetMapping
public List<UserDTO> getAllUsers() {
return userService.findAll();
}
@GetMapping("/{id}")
public UserDTO getUser(@PathVariable final Long id) {
return userService.get(id);
}
@CrossOrigin(origins = "*", allowedHeaders = "*")
@GetMapping("/{email}")
public UserDTO getUserByMail(@PathVariable String email) {
return userService.getByEmail(email);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Long createUser(@RequestBody @Valid final UserDTO userDTO) {
return userService.create(userDTO);
}
@PutMapping("/{id}")
public void updateUser(@PathVariable final Long id, @RequestBody @Valid final UserDTO userDTO) {
userService.update(id, userDTO);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteUser(@PathVariable final Long id) {
userService.delete(id);
}
}
Run Code Online (Sandbox Code Playgroud)
我从我的 angular 应用程序调用 get 的地方:
onSubmit(): void {
this.submitted = true;
this.wrongInput = false;
this.loginService.getLogin<User>(this.loginForm.value.email).subscribe((response) => {
this.tempUser = response;
console.log(this.tempUser);
if (this.loginForm.value.email === this.tempUser.email && this.loginForm.value.password === this.tempUser.password) {
this.localStorageService.save(this.tempUser);
this.router.navigate(['/home']);
console.log(true);
}
else {
this.wrongInput = true;
}
});
}
Run Code Online (Sandbox Code Playgroud)
我还尝试添加一个DevCorsConfiguration:
package com.team13.triviaquiz.triviaquizserver.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@Profile("development")
public class DevCorsConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
}
}
Run Code Online (Sandbox Code Playgroud)
并在 my 中添加了配置文件application.properties:
application.properties
spring.profiles.active=development
#enabling h2 console
spring.h2.console.enabled=true
#fixed URL for H2 (necessary from Spring 2.3.0)
spring.datasource.url=jdbc:h2:mem:triviaquizserver
#turn statistics on
spring.jpa.properties.hibernate.generate_statistics = true
logging.level.org.hibernate.stat=debug
#show all queries
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.type=trace
Run Code Online (Sandbox Code Playgroud)
但仍然没有运气...
Pra*_*ran 11
这个问题背后的原因已经在答案中明确提到,暂时CorsRegistry#allowCredentials(true)不能与默认值一起使用CorsRegistry#allowedOrigins()(默认情况下,如果您没有设置此属性,则允许所有来源,除非CorsRegistry#allowedOriginPatterns()设置了任何一个)
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*")
.allowCredentials(true);
}
};
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中allowCredentials设置为true,同时allowedOrigins未配置,这意味着默认情况下允许所有来源(该allowedOrigins值将为*)。
allowedOrigins或allowedOriginPatterns。在以下代码片段中,allowedOriginPatterns使用了 并将值设置为 -> "https://*.domain.com"。此通配符模式匹配任何来自domain.com的主机和url模式,例如https:microservice.division.domain.com @Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*")
.allowedOriginPatterns("https://*.domain.com");
}
};
}
Run Code Online (Sandbox Code Playgroud)
完整代码片段链接
这可能是由于 Spring 库发生了变化,从而影响了 Spring Boot 2.4.0。看这里https://github.com/spring-projects/spring-framework/issues/26111及其相关票https://github.com/spring-projects/spring-framework/pull/26108
编辑 这里来自第一个链接的原始消息:
#25016 引入了除了 allowedOrigins 之外还可以配置 allowedOriginPatterns 的功能。它允许您定义更灵活的模式,而后者实际上是在 Access-Control-Allow-Origin 标头中返回的值,因此不允许将“*”与 allowCredentials=true 结合使用。更改在 WebMvc 和 WebFlux 配置中引入了等效的 allowedOriginPatterns 方法,但不在 SockJS 配置和 AbstractSocketJsService 中。
我会为 5.3.2 添加那些。然后,您需要切换到 allowedOriginPatterns 而不是 allowedOrigins ,但这使您可以选择更精确地定义允许的域模式。同时,如果可行,您也许可以通过列出特定域来解决。
| 归档时间: |
|
| 查看次数: |
12335 次 |
| 最近记录: |