在 Spring Boot 中使用 Angular 启用 Cors,仍然存在 Cors 错误

2023-11-21

我为所有来源和标头启用了 cors,但当我调用 a 时,我仍然收到 cors 错误get从我的角度应用程序到 Spring Boot 的方法。

来自控制台的 Cors 错误:

Access to XMLHttpRequest at 'http://localhost:8080/api/users/[email protected]' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

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

}

我从我的角度应用程序调用 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;
      }
    });
  }

我还尝试添加一个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:

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

但还是没有运气...


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

EDIT这是来自第一个链接的原始消息:

#25016 除了 allowedOrigins 之外还引入了配置 allowedOriginPatterns 的功能。它让你定义更灵活 模式,而后者实际上是要返回的值 Access-Control-Allow-Origin 标头中不允许使用“*” 与allowCredentials=true 组合。引入的变化 WebMvc 和 WebFlux 中的等效 allowedOriginPatterns 方法 配置,但不在 SockJS 配置和 AbstractSocketJsService 中。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Spring Boot 中使用 Angular 启用 Cors,仍然存在 Cors 错误 的相关文章

随机推荐

  • mod_php是什么?

    在经历一个Zend教程 我遇到了以下声明 请注意 htaccess 中的 php flag 设置仅在您使用 mod php 时才有效 有人能解释一下这是什么意思吗 mod php表示 PHP 作为阿帕奇模块 基本上 加载时mod php作为
  • 使用 2d 数组索引 3d numpy 数组

    我想根据 numpy 3d 数组中的值创建一个 numpy 2d 数组 使用另一个 numpy 2d 数组来确定在轴 3 中使用哪个元素 import numpy as np arr 3d np arange 2 3 4 reshape 2
  • 在 IntelliJ 中调试时是否可以观看 BufferedImage 对象?

    在 IntelliJ 中调试时是否可以观看 BufferedImage 对象 我的意思是查看图像的视觉内容 而不是记忆身份 是否也可以直观地查看自定义对象 即编写一些自定义可视化工具 IntelliJ IDEA 2016 1 1 能够显示B
  • 管理 Firebase 聊天中的未读消息

    我正在构建实时聊天 与 Skype 非常相似 我使用 firebase 作为后端 在客户端使用 Angularfire 基本上 所有事情看起来都很清楚 但我坚持一件事 显示未读消息数 应用程序使用非常简单的 Firebase 设计 2 个或
  • 使用 pdfsharp 添加 acroform

    我如何将带有 pdfsharp lib 的 Acroforms 或任何输入字段 添加到 pdf 中 例如文本框 PdfSharp Pdf AcroForms PdfTextField 我找不到任何示例 只能读取 修改 我找到了 page g
  • 为什么Ajax.BeginForm提交后重定向到新的空页面?

    为什么 Ajax BeginForm 在提交后将我的页面重定向到新的空页面 我的控制器代码是 HttpPost public void ProductCommentAdd int productId string text Do somet
  • 在 Rails 6 中使用 activestorage 时,如何在重新显示表单时保留文件?

    在 Rails 6 中 我有一个带有文件字段的表单 我使用 activestorage 来存储文件 如果提交表单后验证失败 则会重新显示表单并显示验证错误 重新显示表单时如何保留添加到文件字段的文件 以便用户不必再次将文件添加到表单 Rai
  • 在另一个类中处理 JButton 单击事件

    我是来自 C 的 java 新手 所以我不熟悉 java 最佳实践 我有一个主类 它打开 JFrame 以从用户那里获取多个输入字符串 当用户单击 提交 时 GUI 应关闭 主类将继续使用输入进行处理 This is the main cl
  • 如何在 Polymer 2.0 中启用 Shady DOM?

    聚合物 1 x 用途阴暗的 DOM默认情况下 但可以在初始化时通过设置来更改window Polymer导入前的对象polymer html如下 然而 Polymer 2 0 似乎使用影子 DOM不管window Polymer dom s
  • Twitter bootstrap:模式淡入淡出

    我的 twitter bootstrap 模式有问题 当我没有的时候它工作得很好 fade我的元素上的类 一旦我添加它 模式就不会显示 我将问题追查到这一行 我认为 doAnimate this backdrop one transitio
  • 如何使用 cmake 设置嵌套子目录的 Visual Studio 过滤器

    我有以下结构 Main dir CMakeLists txt File cpp File hpp Dir dir CMakeLists txt File1 cpp File1 hpp File2 cpp File2 hpp 主要 CMake
  • 如何对对象数组进行字符串化?

    我创建了一个需要存储并保留到另一个页面的对象数组 对象数组与此类似 var cheese array name Chedder age 34 smelly true name Brie age 4 smelly false name Blu
  • IE 中的 HTML 实体和字符集

    我正在显示 html 实体 10003 复选标记 在使用 iso 8859 1 作为字符集的 html 文档中 在 Firefox 中 它显示为复选标记 在 IE 中 它显示为一个方框 切换到 UTF 8 似乎没有什么区别 有没有一种可靠的
  • Javascript正则表达式字符串中的货币符号

    所以我有一个格式化字符串可以是 00 or 00我想获取货币符号 这里是我正在使用的代码 currencySymbol format match p Sc 我希望currencySymbol 等于 或 但它不起作用 currencySymb
  • MS SQL Server - 通过网络批量插入

    我有一个使用 MS SQL Server 的应用程序 我需要从文件中进行批量插入 症结在于数据库和我的应用程序将托管在不同的服务器上 通过网络进行批量插入的最佳方法是什么 到目前为止我想到的两个想法 从应用程序服务器共享数据库服务器可以找到
  • 无法使用bundle exec找到rake

    当我尝试执行 捆绑执行耙任何东西 我收到错误 Could not find rake 10 1 0 in any of the sources Run bundle install to install missing gems 但是当我执
  • 线程化 Delphi ADO 查询

    我有一个查询代码 每次需要从数据库获取数据时都可以调用它 并且我希望它是线程化的 不知道如何在线程中实现此代码 以便我可以重用此代码 基本上 我希望此代码在线程中 我知道如何在线程内创建一个简单的数据库查询 但想要一些可以重用的东西 谁能指
  • JavaScript获取url段和参数

    我读过一些问题 但我仍然不知道该怎么做我有一个网址example com event 14aD9Uxp p 10 在这里我想得到14aD9Uxp和 p 的值我尝试过使用split p 但这不起作用我想使用正则表达式 但我不太明白如何使用它
  • 在桌面上运行时如何将 Windows 10 通用应用程序的窗口最大化至全屏?

    使用 Windows 10 或 Windows 8 1 WinRT 构建通用应用程序时 是否可以强制应用程序的主窗口在启动时最大化 这显然是应用程序在移动设备上运行时的自然行为 但在桌面上运行时则不然 使用 WinForms 这当然是可能的
  • 在 Spring Boot 中使用 Angular 启用 Cors,仍然存在 Cors 错误

    我为所有来源和标头启用了 cors 但当我调用 a 时 我仍然收到 cors 错误get从我的角度应用程序到 Spring Boot 的方法 来自控制台的 Cors 错误 Access to XMLHttpRequest at http l