基本 GET 请求失败 Angular 和 Spring [英] Basic GET request failed Angular and Spring

查看:22
本文介绍了基本 GET 请求失败 Angular 和 Spring的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

让我分享我的 Java 和 Angular 代码.

Java 代码

@RestController @CrossOrigin(origins = "http://localhost:4200")公共课主要{@RequestMapping("/hello")public Map家(){映射<字符串,对象>模型 = new HashMap();model.put("id", UUID.randomUUID().toString());model.put("content", "Hello from Backend");退货模式;}}

Angular 侧 auth.componen.ts 文件

import { HttpClient } from '@angular/common/http';从'@angular/forms' 导入 { NgForm };从@angular/core"导入{组件};@成分({选择器:'app-auth',templateUrl: './auth.component.html'})导出类 AuthComponent{isLoginMode = true;title = '演示';问候 = {};onSwitchMode(){this.isLoginMode = !this.isLoginMode;}onSubmit(形式:NgForm){控制台日志(表单值);表单.重置();}构造函数(私有http:HttpClient){http.get('http://localhost:8080/hello').subscribe(data => this.greeting = data);}}

HTML 端

<h1>欢迎{{title}}!<div class="container"><p>Id:<span>{{greeting.id}}</span></p><p>消息:<span>{{greeting.content}}!</span></p>

我正在关注

Chrome 开发者工具网络标签结果:

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

解决方案

使用 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 的最简单方法是使用CorsFilter

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

@EnableWebSecurity公共类 WebSecurityConfig 扩展WebSecurityConfigurerAdapter {@覆盖protected void configure(HttpSecurity http) 抛出异常 {http//如果 Spring MVC 在类路径上并且没有提供 CorsConfigurationSource,//Spring Security 将使用提供给 Spring MVC 的 CORS 配置.cors().and()...}}

I am trying to make a simple request from angular to spring. I used bare bone spring web and spring security and simple angular(9) request.

Let me share my Java and Angular code.

Java Code

@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 side auth.componen.ts file

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 side

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

I am following the this link but every time I get this error:

Edit 1: Chrome developer tools Network tab result:

I tried to search online but can't find the answer. Can you help me to continue?

解决方案

With Spring Security, Cors filter is to be additionally configured.

Here is the reference from Spring Documentation 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

Cors filter can simply be configured through 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()
        ...
    }
}

这篇关于基本 GET 请求失败 Angular 和 Spring的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆