【问题标题】:Unable to hit spring boot Rest API from my angular 5 project无法从我的 Angular 5 项目中访问 Spring Boot Rest API
【发布时间】:2019-01-12 04:56:20
【问题描述】:

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

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

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

【问题讨论】:

  • 您必须在后端启用 CORS
  • 或者配置ng serve作为localhost:8080的代理
  • 好吧,我用 @CrossOrigin 注释了我的控制器,它起作用了。但这有什么副作用?这只是一个临时解决方案吗?它是否适用于企业级实时应用程序。

标签: angular mongodb spring-boot


【解决方案1】:

我建议使用角度代理配置。

1) 在前端根目录(package.json 文件旁边)创建一个新文件。您可以随意命名文件,例如 proxy.config.json。 此文件包含一个 javascript 对象。

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

2) 将 'ng start' 脚本改成 package.json 为 "start": "ng serve --proxy-config proxy.config.json"

3) 重启 cli 服务器(如有必要)

从您的 angular-cli 服务器到 /api 的每次调用都将被重定向到 http://localhost:8080/api 。这样你就不用去接触 CORS 配置,也不会影响生产安全。

【讨论】:

  • 酷,这对我有用,而且我知道我们可以在需要时更改配置。 ;) 非常感谢大卫 G。
【解决方案2】:

您需要在基于 Spring Boot 的微服务中允许 CORS (cross-origin resource sharing)。

Pivotal Team 的这篇教程很好地解释了如何在 Spring Boot 应用程序中实现 CORS 支持:

https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

如果您使用的是 Spring Boot,建议只声明一个 WebMvcConfigurer bean,如下所示:

@Configuration
 public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
 }

【讨论】:

    猜你喜欢
    • 2018-04-08
    • 2018-03-29
    • 1970-01-01
    • 2021-03-23
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 2021-06-10
    相关资源
    最近更新 更多