Mertalp Tasdelen
Mertalp Tasdelen

Reputation: 190

Basic GET request failed Angular and Spring

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: Error message I get

Edit 1: Chrome developer tools Network tab result: Network Tab on Chrome

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

Upvotes: 0

Views: 358

Answers (2)

SKumar
SKumar

Reputation: 2030

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

Upvotes: 1

Cezary Butler
Cezary Butler

Reputation: 857

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

Upvotes: 1

Related Questions