Basic GET request failed Angular and Spring

蹲街弑〆低调 提交于 2021-01-29 15:30:38

问题


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?


回答1:


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



回答2:


Screenshot from the console explains quite well why it failed. For sure you're running angular application on different URL than the spring one.

In order to allow the angular application to communicate with the spring backend, you need to configure CORS policy on the backend which is covered here

Looks like your browser for some reason didn't send a preflight request. Maybe you'll find explanation on MDN



来源:https://stackoverflow.com/questions/63140625/basic-get-request-failed-angular-and-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!