Spring Boot/Http call angular 2没有角度的``Access-Control-Allow-Origin'' [英] No 'Access-Control-Allow-Origin' in angular with Spring-boot / Http call angular 2

查看:102
本文介绍了Spring Boot/Http call angular 2没有角度的``Access-Control-Allow-Origin''的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 spring boot server 将数据发送到 角度应用程序 通过 角度http通话 .另外,我还为Spring Boot应用程序添加了 security 依赖项.

I'm trying to get data to angular application from spring boot server via angular http call. Also I have added security dependency for spring boot application.

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

When I'm trying with browser this will come.

一旦我在Intellij控制台中用密码输入了密码,它将显示响应.

Once I enter them with the password in console of Intellij it will show the response.

当我尝试使用角度http调用时,它失败并显示错误 主题.

When I'm trying with angular http call it fails and show error on topic.

我的角度组件具有以下代码.

My angular component has following code.

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

我的spring boot应用程序具有以下代码

My spring boot application has below code

@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)的信息,但目前尚不清楚如何将其应用于有角度的资源.

Also i have read about Cross-Origin Resource Sharing (CORS) but it is unclear how to apply those to angular.

我的错误是:

推荐答案

我在角度应用中所做的事情是正确的,必须纠正 仅限我的spring boot应用程序.

What I have done in angular application was correct and had to correct my spring boot application only.

我所做的唯一更改是创建名为 WebSecurityConfig的配置文件.

The only change I made is creating configuration file called 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;
    }
}

这篇关于Spring Boot/Http call angular 2没有角度的``Access-Control-Allow-Origin''的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆