【问题标题】:Basic GET request failed Angular and Spring基本 GET 请求失败 Angular 和 Spring
【发布时间】:2020-11-18 06:39:55
【问题描述】:

我正在尝试从 angular 到 spring 提出一个简单的请求。我使用了裸骨弹簧网和弹簧安全性以及简单的 angular(9) 请求。

让我分享一下我的 Java 和 Angular 代码。

Java 代码

@RestController @CrossOrigin(origins = "http://localhost:4200")
public class Main {

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

Angular 端 auth.componen.ts 文件

import { HttpClient } from '@angular/common/http';
import { NgForm } from '@angular/forms';
import { Component } from '@angular/core';


@Component({
    selector: 'app-auth',
    templateUrl: './auth.component.html'
})
export class AuthComponent{
    isLoginMode = true;
    title = 'Demo';
    greeting = {};

    onSwitchMode(){
        this.isLoginMode = !this.isLoginMode;
    }

    onSubmit(form: NgForm){
        console.log(form.value);
        form.reset(); 
    }

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

HTML 方面

<div style="text-align:center"class="container">
  <h1>
    Welcome {{title}}!
  </h1>
  <div class="container">
    <p>Id: <span>{{greeting.id}}</span></p>
    <p>Message: <span>{{greeting.content}}!</span></p>
  </div>
</div>

我正在关注this link,但每次我收到此错误时:

编辑 1: Chrome 开发者工具 Network 标签结果:

我试图在网上搜索,但找不到答案。你能帮我继续吗?

【问题讨论】:

  • 我看到您启用了带有注释的 cors。只是为了确保您的 Angular 应用程序在 localhost:4200 上运行?
  • 你好 @CezaryButler 是的,我的 Angular 应用程序在 localhost:4200 上运行,我的请求页面是 localhost:4200/auth
  • 您能否发布带有预检请求的 Chrome 网络标签的一部分?尽管存在注释,但似乎弹簧没有添加 Access-Control-Allow-Origin 标头。
  • 我编辑了我的问题。

标签: spring spring-mvc spring-security cors angular9


【解决方案1】:

使用 Spring Security,需要额外配置 Cors 过滤器。

这是来自 Spring 文档https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/cors.html的参考

Spring Framework 为 CORS 提供一流的支持。 CORS 必须在 Spring Security 之前处理,因为飞行前请求将不包含任何 cookie(即 JSESSIONID)。如果请求中不包含任何 cookie 且 Spring Security 优先,则请求将确定用户未通过身份验证(因为请求中没有 cookie)并拒绝它。

确保首先处理 CORS 的最简单方法是使用 过滤器

Cors 过滤器可以通过 WebSecurityConfigurerAdapeter 简单配置

@EnableWebSecurity
public class WebSecurityConfig extends 
WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        // if Spring MVC is on classpath and no CorsConfigurationSource is provided,
        // Spring Security will use CORS configuration provided to Spring MVC
        .cors().and()
        ...
    }
}

【讨论】:

  • 感谢您的回答,抱歉迟到了。
【解决方案2】:

控制台的屏幕截图很好地解释了失败的原因。确保您在不同于 spring 的 URL 上运行 Angular 应用程序。

为了让 Angular 应用程序与 Spring 后端进行通信,您需要在后端配置 CORS 策略,该策略已覆盖here

您的浏览器似乎由于某种原因没有发送预检请求。 也许你会在MDN找到解释

【讨论】:

  • 你好,你可以看到我的Java代码有一个注解为@CrossOrigin。
  • @MertalpTasdelen 我已经验证过,确实需要使用 spring-security 额外的 cors 过滤器配置,如 user11244881 回答中所示
  • 非常感谢您的时间安排。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-22
  • 2021-10-08
  • 2021-11-05
  • 2013-01-15
  • 1970-01-01
  • 2015-06-21
  • 1970-01-01
相关资源
最近更新 更多