基本GET请求失败Angular和Spring

基本GET请求失败Angular和Spring

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

问题描述

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

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.

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

Let me share my Java and Angular code.

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

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端

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

我正在跟踪

Chrome开发人员工具的网络"标签结果:

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?

推荐答案

使用Spring Security,还需要另外配置Cors过滤器.

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

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

Here is the reference from Spring Documentation https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/cors.html

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

The easiest way to ensure that CORS is handled first is to use theCorsFilter

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:08