首页 > 解决方案 > 无法从我的 Angular 5 项目中访问 Spring Boot Rest API

问题描述

我正在准备一个基于微服务的示例应用程序,我想在其中使用用 Spring Boot 编写的后端 API。现在我希望它从我的 Angular 5 UI 应用程序中运行。

但低于错误。我做了 ctrl+F12 并且从控制台我得到了以下错误。

无法加载http://localhost:8080/contacts:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问源“ http://localhost:4200 ”。

标签: angularmongodbspring-boot

解决方案


I suggest to use an angular proxy configuration.

1) Create a new file in the frontend root directory (next to package.json file). You can name is file whatever you want, proxy.config.json for example. This files contains a javascript object.

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

2) Change the 'ng start' script into package.json to "start": "ng serve --proxy-config proxy.config.json"

3) Restart the cli server (if necessary)

Each calls from your angular-cli server to /api will be redirected to http://localhost:8080/api . This way, yo don't have to touch the CORS config and will not affect the production security.


推荐阅读