【问题标题】:No 'Access-Control-Allow-Origin' Angular->SpringBoot没有'Access-Control-Allow-Origin' Angular-> SpringBoot
【发布时间】:2018-12-12 19:05:01
【问题描述】:

我正在尝试将 Angular2 称为 SpringBoot 的一项服务,但是当我调用时出现此错误:

在我的 SpringBoot 中,我有:

package com.service.configure;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = "com.service")
public class ServiciosConfig  extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/").permitAll().anyRequest().authenticated().and().httpBasic().and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 
    }


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
         auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER");

    } 

}

在 Angular2 中:

private fetchData() {
        const url = 'http://localhost:8080/pg/get';
        this.service.fetchData(url).subscribe(
            data => {
                console.log('mis datos ', data);
                this.headers = data[0].headers;
                this.params = data[1].params;
            });
    }
 public fetchData(url: string): Observable<any> {
    let headers = new Headers();
    headers.append("Authorization", "Basic YWRtaW46YWRtaW4=");
    return this.http.get<Object[]>(url);
  }

如果我输入http://localhost:8080/pg/get 我可以得到数据 =)。

但是如果我尝试使用 Angular 是不可能的......

我的朋友使用了“邮递员”,他收到了数据

代码邮递员:

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://myIp:8080/pg/get",
  "method": "GET",
  "headers": {
    "Authorization": "Basic YWRtaW46YWRtaW4=",
    "Cache-Control": "no-cache",
    "Postman-Token": "e1225c81-8cb0-4809-9a2a-c82776793906"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});​

我的控制器:

@RestController
@RequestMapping(value={"/pg"})
@CrossOrigin
public class PgController {

    @Autowired
    PgService pgRepository;

    @RequestMapping(method=RequestMethod.GET,value="/", produces = MediaType.APPLICATION_JSON_VALUE)
    String home() {
        return "¡Servicio configuración!";
    }


    @RequestMapping(method=RequestMethod.GET,value="/get", produces = MediaType.APPLICATION_JSON_VALUE)
    public List<tp_parametros_generales> getAllParameters() {
        List<tp_parametros_generales> tasks = pgRepository.getPg();
        return tasks;
    }
}

【问题讨论】:

标签: angular spring-boot


【解决方案1】:

对于开发,您可以添加:

@CrossOrigin()

对控制器的注释。它应该可以工作。

【讨论】:

  • 你好,我有@CrossOrigin()
  • @EduBw h..这很奇怪..你的 API url 是正确的?
  • 是的,我的朋友通过 http://myIp:8080/pg/get" 获取数据,但 Angular 没有。
【解决方案2】:

在你的控制器类上使用@CrossOrigin注解,或者你可以创建一个配置文件来启用CrossOrigin

【讨论】:

    【解决方案3】:

    另一种方法是使用 angular-cli 的 /webpack-dev-servers 代理支持。

    https://github.com/angular/angular-cli/wiki/stories-proxy

    这样您就可以将 angulars http://localhost:4200/pg 映射到您的 Spring Boot 服务器。 而且由于它们现在位于同一个域中,因此您不会遇到任何跨域问题。

    然后当你上线时,你使用 nginx 代理做同样的事情。

    【讨论】:

      【解决方案4】:

      我可以解决的

      public class ServiciosConfig  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;
              }
      
          }
      

      【讨论】:

        猜你喜欢
        • 2017-10-18
        • 1970-01-01
        • 2019-04-10
        • 1970-01-01
        • 2017-06-15
        • 2019-01-05
        • 2016-01-21
        • 2018-02-02
        • 1970-01-01
        相关资源
        最近更新 更多