【问题标题】:No 'Access-Control-Allow-Origin' in angular with Spring-boot / Http call angular 2 [duplicate]Spring-boot / Http call angular 2的角度没有'Access-Control-Allow-Origin' [重复]
【发布时间】:2018-08-01 20:00:54
【问题描述】:

我正在尝试将数据从 spring boot server 获取到 angular 应用程序 通过 angular http 调用。我还为 Spring Boot 应用程序添加了 security 依赖项。

当我尝试使用浏览器时,它会出现。

一旦我在 Intellij 的控制台中输入密码,它就会显示响应。

当我尝试使用 angular http 调用时,它会失败并显示错误 主题。

我的角度组件有以下代码。

constructor(private http: HttpClient) { 
    http.get('http://localhost:8080/resource').subscribe(data => this.greeting = data);
}

我的 Spring Boot 应用程序有以下代码

@RequestMapping("/resource")
public Map<String,Object> home() {
      Map<String,Object> model = new HashMap<String,Object>();
      model.put("id", UUID.randomUUID().toString());
      model.put("content", "Hello World");
      return model;
}

我也读过跨域资源共享(CORS),但不清楚如何将这些应用到角度。

我的错误是:

【问题讨论】:

  • 与角度无关。您必须在服务器中启用 CORS。查看如何在您的服务器中执行此操作。
  • 我想我必须修复有角的一面。谢谢你
  • 基本上,您必须在服务器的 HTTP 选项响应的标头中将 Access-Control-Allow-Origin 设置为您的 url。
  • 这篇文章可能对你有帮助:spring.io/guides/gs/rest-service-cors/#_enabling_cors
  • @CrossOrigin(origins = "*") 对此不起作用。 @NiK648。

标签: angular spring-boot cors


【解决方案1】:

检查服务器是否也接受http方法'OPTIONS'。因为如果域不同,浏览器默认发送 OPTIONS 请求,响应应该是成功 200。如果它是一个弹簧后端

public class CorsFilter implements Filter {

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    final HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
    if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        chain.doFilter(req, res);
    }
}

【讨论】:

  • 因为我是新手,你能解释一下把这段代码放在哪里吗?
  • 我认为你的答案会和我的一致。请告诉我如何将其应用于我的代码。 @VithuBati
  • 在过滤器本身,你可以放。如果它解决了您的问题,我更新了我的代码并接受它作为正确答案。
【解决方案2】:

控制器中的每个方法都需要单独允许跨域。只需在方法顶部添加 @CrossOrigin(origins = "*"),希望这能解决问题。

@CrossOrigin(origins = "*")
@RequestMapping("/resource")
    public Map<String,Object> home() {
        Map<String,Object> model = new HashMap<String,Object>();
        model.put("id", UUID.randomUUID().toString());
        model.put("content", "Hello World");
        return model;
}

【讨论】:

  • 不,我试过了。它不起作用。我不应该在这里设置 Access-Control-Allow-Credentials 吗?
  • 你不需要;只需为方法添加 Method 类型,例如 GET 或 POST。
  • 你的意思是@GetMapping(path = "/resource")
  • 不,我试过了。它说请求的资源上不存在“Access-Control-Allow-Origin”标头。
【解决方案3】:

在 scala + spring boot 中可以添加 cors 映射

class WebAppConfig extends WebMvcAutoConfigurationAdapter {

  @Value("${cors.origin}")
  private val corsOrigin: String = "all"

  override def addCorsMappings(registry: CorsRegistry): Unit = {
    if(corsOrigin=="all"){
      registry.addMapping("/**")
    }else{
      registry.addMapping("/**").allowedOrigins(corsOrigin.split(","):_*)
    }
  }

}

【讨论】:

    【解决方案4】:

    我在角度应用程序中所做的事情是正确的,必须纠正 仅限我的 Spring Boot 应用程序。

    我所做的唯一更改是创建名为 WebSecurityConfig.

    的配置文件
    @EnableWebSecurity
    @Configuration
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors();
        }
    
        @Bean
        CorsConfigurationSource corsConfigurationSource() {
            UrlBasedCorsConfigurationSource source = new
                    UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
            return source;
        }
    }
    

    【讨论】:

    猜你喜欢
    • 2020-05-27
    • 1970-01-01
    • 2015-01-20
    • 2018-06-21
    • 2018-12-12
    • 2014-12-15
    • 2019-02-28
    • 2017-11-14
    • 2023-01-13
    相关资源
    最近更新 更多