首页 > 解决方案 > 基本 GET 请求失败 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;
    }
}

角端 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>

我正在关注此链接,但每次收到此错误时: 我收到的错误消息

编辑 1:Chrome 开发者工具网络选项卡结果: Chrome 上的网络标签

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

标签: springspring-mvcspring-securitycorsangular9

解决方案


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

为了允许 Angular 应用程序与 Spring 后端进行通信,您需要在后端配置 CORS 策略,此处介绍

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


推荐阅读