基本 GET 请求失败 Angular 和 Spring

Basic GET request failed Angular and Spring

我正在尝试从 angular 向 spring 提出一个简单的请求。我使用了简单的 spring 网络和 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 开发人员工具网络选项卡结果:

我尝试在线搜索但找不到答案。你能帮我继续吗?

控制台的屏幕截图很好地解释了失败的原因。可以肯定的是,您 运行 angular 申请的 URL 与 spring 不同。

为了让angular应用程序与spring后端通信,您需要在覆盖here

的后端配置CORS策略

您的浏览器似乎出于某种原因没有发送预检请求。 也许您会在 MDN

上找到解释

使用 Spring 安全性,需要额外配置 Cors 过滤器。

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

Spring Framework provides first class support for CORS. CORS must be processed before Spring Security because the pre-flight request will not contain any cookies (i.e. the JSESSIONID). If the request does not contain any cookies and Spring Security is first, the request will determine the user is not authenticated (since there are no cookies in the request) and reject it.

The easiest way to ensure that CORS is handled first is to use the CorsFilter

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

@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()
        ...
    }
}