在Spring Boot中使用Angular启用了cors,仍然出现cors错误 [英] Cors enabled in Spring Boot with Angular, still cors errors

查看:112
本文介绍了在Spring Boot中使用Angular启用了cors,仍然出现cors错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为所有来源和标头启用了cors,但是当我从有角度的应用程序调用 get 方法以启动弹簧时,仍然出现cors错误.

I have cors enabled for all origins and headers but I still get an cors error when I call a get method from my angular app to spring boot.

控制台错误:

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.

我的 controller (我叫getbyemail):

My controller (I call the 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);
    }

}

我在我的有角度应用程序中调用get的地方:

Where I call the get from my angular app:

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;
      }
    });
  }

我还尝试添加 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");
    }
}

并将配置文件添加到我的 application.properties 中:

And added the profile in 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

但还是没有运气...

But still no luck...

推荐答案

这可能是由于Spring库中的更改,从而影响了Spring Boot 2.4.0.在这里查看 https://github.com/spring-projects/spring-framework/issue/26111 及其相关票证 https://github.com.com/spring-projects/spring-framework/pull/26108

This could be due to a change in Spring libraries, thus affecting Spring Boot 2.4.0. Look here https://github.com/spring-projects/spring-framework/issues/26111 and to its related ticket https://github.com/spring-projects/spring-framework/pull/26108

编辑这里是来自第一个链接的原始消息:

EDIT Here the original message from the 1st link:

#25016引入了仅配置allowedOrigins的功能,还可以配置allowedOriginPatterns.它让您定义更灵活模式,而后者实际上是要在Access-Control-Allow-Origin标头,对于该"*",不允许进入与allowCredentials = true结合使用.引入的变化WebMvc和WebFlux中的等效allowedOriginPatterns方法配置,但不在SockJS配置和AbstractSocketJsService中.

#25016 introduced the ability to configure allowedOriginPatterns in addition to just allowedOrigins. It lets you define more flexible patterns while the latter is literally the value to return in the Access-Control-Allow-Origin header and for that "*" is not allowed in combination with allowCredentials=true. The change introduced equivalent allowedOriginPatterns methods in the WebMvc and the WebFlux config, but not in the SockJS config and the AbstractSocketJsService.

我将为5.3.2添加它们.然后,您需要切换到allowedOriginPatterns而不是allowedOrigins,但这给了你一个选项以更精确地定义允许的域模式.在里面同时,您可能可以通过列出特定域,如果可行的话.

I'll add those for 5.3.2. You'll then need to switch to allowedOriginPatterns instead of allowedOrigins but that gives you an option to define more precisely the allowed domain patterns. In the mean time, you might be able to work around by listing specific domains if that's feasible.

这篇关于在Spring Boot中使用Angular启用了cors,仍然出现cors错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆