【问题标题】:CORS error connecting Angular to Spring (localhost 8080 <--> localhost 4200)将 Angular 连接到 Spring 的 CORS 错误(localhost 8080 <--> localhost 4200)
【发布时间】:2020-05-08 17:44:13
【问题描述】:

我正在尝试将 Angular 8 中的前端连接到使用 Spring 用 Ja​​va 编写的后端。

我的 Spring 后端在 localhost:8080 的 Tomcat 服务器上运行,Angular 在 localhost:4200 上打开。 当我尝试注册用户(或执行任何操作)时,我收到此错误:

从 'http://localhost:8080/Revvit/users' 访问 XMLHttpRequest 来源“http://localhost:4200”已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。

在 Spring 中的 UserController 类中,我用

注释了控制器
@CrossOrigin(origins= "*", allowedHeaders="*")
@Controller
public class UserController {............

但是,我的控制台中仍然收到与上述相同的消息。

所以,我假设我必须在我的 Angular 项目中添加一些允许 CORS 的标头,但是我将在哪里以及如何合并它?

【问题讨论】:

  • 我认为这个链接可能有用spring.io/guides/gs/rest-service-cors
  • 如果您有状态请求,则不允许跨源 *!
  • 您应该尝试在控制器中添加不带参数的“@CrossOrigin”,然后在 DEBUG 级别激活 log4j 或 logback conf 中的“org.apache.http.headers”日志类别以查看发生了什么(是否存在预期的响应标头?)。

标签: java angular spring http cors


【解决方案1】:

您可以通过将 proxy.conf 文件添加到您的项目来解决它,如 Angular 文档:https://angular.io/guide/build#proxying-to-a-backend-server

使用 proxy.conf 文件,您可以将您在应用中使用的特定端点设置为不同的目标,例如:

{
  "/Revvit": {
    "target": "http://localhost:8080",
    "secure": false
  }
}

然后您可以使用 HttpClient 服务获取:

this.http.get('Revvit/users')

并获得预期的行为

【讨论】:

    【解决方案2】:

    我已经用

    注释了我的控制器
    @CrossOrigin(origins = "http://localhost:4200")
    

    它有效。

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 2020-10-11
      • 2021-08-14
      • 2019-05-27
      • 1970-01-01
      • 2019-09-10
      • 2018-11-15
      • 1970-01-01
      • 2021-01-20
      相关资源
      最近更新 更多