【问题标题】:Cors Auth SpringBootCors Auth Spring Boot
【发布时间】:2021-07-27 09:59:08
【问题描述】:

我正在使用 springboot 和 angular。 尝试使用 JWT 登录,当使用邮递员发送 http 时,请求是可以的,但是当尝试使用 Angular 发送相同的 http 时,我得到了下一个错误:

从源访问“http://localhost:8080/login”处的 XMLHttpRequest “http://localhost:4200”已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:它没有 HTTP 正常状态。

zone-evergreen.js:2845 POST http://localhost:8080/login 网络::ERR_FAILED

当我发送登录以外的请求时,它们工作正常 我知道需要一个 cors 所以代码是下一个:

@EnableGlobalMethodSecurity(securedEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().authenticated().and().csrf().disable().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().cors();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    org.springframework.web.cors.CorsConfiguration configuration = new org.springframework.web.cors.CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
    configuration.setAllowedMethods(Arrays.asList("*"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

但错误是一样的。

【问题讨论】:

  • 当然,因为您的 BE 与弹簧靴的来源与角度不同。您可以在 Angular 应用程序中设置您的 proxy.conf.json

标签: java angular spring-boot cors token


【解决方案1】:

您可以在 Angular 应用中使用 proxy.conf.json。

这是proxy.conf.json的例子

{
  "/api/*": {
      "target": "http://localhost:8080",
      "secure": false,
      "logLevel": "debug",
      "pathRewrite": {
        "^/api" : ""
      }
  }
}

然后你就可以使用http://localhost:4200/api/path-be点击你的BE了

http://localhost:4200 是您的 Angular 应用程序。 /api 如果您向/api/* 发出请求,那么角度代理配置将重定向到您在proxy.conf.json 中定义的BE

记得将proxy.conf.json 添加到您的angular.json

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "angular-hands-on:build",
            "proxyConfig": "proxy.conf.json"
          },

重启你的 Angular 应用

【讨论】:

  • 谢谢!!!注意:我在 package.json 上添加“start”:“ng serve --proxy-config proxy.conf.json”并使用 NPM START 而不是 NG SERVE 运行项目
  • 非常感谢,如果它可以提供帮助。
猜你喜欢
  • 2021-03-15
  • 2016-05-04
  • 2019-07-16
相关资源
最近更新 更多