将Angular连接到Spring的CORS错误(localhost 8080 <-> localhost 4200)

时间:2020-01-22 14:24:20

标签: java angular spring http cors

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

我的Spring后端在Tomcat服务器上的localhost:8080上运行,而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的标题,但是在哪里,我将如何合并呢?

1 个答案:

答案 0 :(得分:0)

您可以通过将proxy.conf文件添加到项目中来解决它,如下所示: 角度文档: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')

并获得预期的行为