title: Spring boot with Angular. Access to XMLHttpRequest at 'http://localhost:8080/' from origin 'http://localhost:4200' has been blocked by CORS policy
body: <p>My Angular application is running on <a href="http://localhost:4200" rel="noreferrer">http://localhost:4200</a> port and Spring Boot on <a href="http://localhost:8080" rel="noreferrer">http://localhost:8080</a> port.
  When I PUT request from client side I get this error.</p>
  
  <p>I tried to create headers by doing:</p>
  
  <pre><code>headers = new HttpHeaders({'Access-Control-Allow-Origin' : '*'})
  </code></pre>
  
  <p>and then put headers variable in PUT request like this: </p>
  
  <pre><code>this.http.put("//localhost:8080/save-account", accountForm, 
  {headers: this.headers}).subscribe(
        res =&gt; console.log(res),
        err =&gt; console.log(err)
  )
  </code></pre>
  
  <p>But nothing worked out.</p>
  
  <hr>
  
  <p>My code :</p>
  
  <p>Server side controller:</p>
  
  <pre><code>package com.tigran.chagmo.controllers;
  
  import com.tigran.chagmo.models.AccountRepository;
  
  import java.util.Collection;
  
  import com.tigran.chagmo.entities.Account;
  
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.web.bind.annotation.CrossOrigin;
  import org.springframework.web.bind.annotation.DeleteMapping;
  import org.springframework.web.bind.annotation.GetMapping;
  import org.springframework.web.bind.annotation.PathVariable;
  import org.springframework.web.bind.annotation.PostMapping;
  import org.springframework.web.bind.annotation.PutMapping;
  import org.springframework.web.bind.annotation.RequestBody;
  import org.springframework.web.bind.annotation.RequestMapping;
  import org.springframework.web.bind.annotation.RestController;
  
  @RestController
  @CrossOrigin(origins="http://localhost:4200")
  public class HomeController{
  
      @Autowired
      AccountRepository accRepo;
  
      @PutMapping("/update-account")
      public Account putAccount(@RequestBody Account account){
          accRepo.save(account);
          return account;
      }
  
  }
  </code></pre>
  
  <p>Client side Typescript files.</p>
  
  <p>Angular app.module.ts file:</p>
  
  <pre><code>import { BrowserModule } from '@angular/platform-browser';
  import { NgModule } from '@angular/core';
  
  import { AppRoutingModule } from './app-routing.module';
  import { AppComponent } from './app.component';
  import { Routes, RouterModule } from '@angular/router';
  import { HomeComponent } from './home/home.component';
  import { NotFoundComponent } from './not-found/not-found.component';
  import { SignUpComponent } from './sign-up/sign-up.component';
  import { LinksService } from './links/links.service';
  import { FormsModule } from '@angular/forms';
  import { AccountService } from './account-service/account.service';
  import { HttpClientModule } from '@angular/common/http';
  
  const appRoutes: Routes = [
    {
      path: '',
      component: HomeComponent
    },
    {
      path: 'home',
      component: HomeComponent
    },
    {
      path: 'sign-up',
      component: SignUpComponent
    },
    {
      path: '**',
      component: NotFoundComponent
    }
  ]
  
  @NgModule({
    declarations: [
      AppComponent,
      HomeComponent,
      NotFoundComponent,
      SignUpComponent
    ],
    imports: [
      BrowserModule,
      AppRoutingModule,
      FormsModule,
      HttpClientModule,
      RouterModule.forRoot(appRoutes)
    ],
    providers: [
      LinksService,
      AccountService
    ],
    bootstrap: [AppComponent]
  })
  export class AppModule { }
  </code></pre>
  
  <p>Angular sign-up component ts file:</p>
  
  <pre><code>import { Component, OnInit } from '@angular/core';
  import { LinksService } from '../links/links.service';
  import { AccountService } from '../account-service/account.service';
  
  @Component({
       selector: 'app-sign-up',
       templateUrl: './sign-up.component.html',
       styleUrls: ['./sign-up.component.css']
  })
  export class SignUpComponent implements OnInit {
  
  constructor(private links: LinksService, 
          private accountService: AccountService) { }
  
  getHome(){
       this.links.getHome();
  }
  
  save(accountForm: any){
       this.accountService.update(accountForm);
  }
  
  ngOnInit(){
       this.accountService.getAll();
  }
  }
  </code></pre>
  
  <p>Account service ts file:</p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import { HttpClient } from '@angular/common/http';
  
  @Injectable({
    providedIn: 'root'
  })
  export class AccountService {
  
     constructor(private http: HttpClient) { }
  
     getAll(){
       return this.http.get("//localhost:8080/accounts")
     }
  
     getOne(id: number){
       return this.http.get("//localhost:8080/account/"+id);
     }
  
     update(accountForm: any) {
       this.http.put("//localhost:8080/save-account", 
     accountForm).subscribe(
         res =&gt; console.log(res),
         err =&gt; console.log(err)
     )
   }
  }
  </code></pre>
  
  <p>Sign-up component html file:</p>
  
  <pre><code>  &lt;form #accountForm="ngForm" (ngSubmit)="save(accountForm.value)" class="text-center border border-light p-5" &gt;
      &lt;label for="gmail" &gt;Gmail&lt;/label&gt;
      &lt;input 
      ngModel name="gmail"
      id="gmail" 
      class="form-control mb-4" 
      tpye="text" &gt;
      &lt;label for="name" &gt;Name&lt;/label&gt;
      &lt;input 
      ngModel name="name"
      id="name" 
      class="form-control mb-4" 
      tpye="text" &gt;
      &lt;label for="username" &gt;Username&lt;/label&gt;
      &lt;input 
      ngModel name="username"
      id="username" 
      class="form-control mb-4" 
      tpye="text" &gt;
      &lt;label for="password" &gt;Password&lt;/label&gt;
      &lt;input 
      ngModel name="password"
      id="password" 
      class="form-control mb-4" 
      tpye="text" &gt;
      &lt;label for="repeat-password" &gt;Repeat password&lt;/label&gt;
      &lt;input 
      ngModel name="repeat-password"
      id="repeat-password"
      class="form-control mb-4" 
      tpye="text" &gt;
      &lt;button [disabled]="!accountForm.valid" class="btn btn-info btn-block my-4" &gt;Sign up&lt;/button&gt;
      &lt;p class="text-left" &gt;Already have an account? &lt;a routerLink="{{ getHome() }}" class="text-primary text-right"&gt;Log in&lt;/a&gt;&lt;/p&gt;
    &lt;/form&gt;
  </code></pre>
  
  <p>After filling the form via browser and sending data. I get this error.</p>
  
  <pre><code> Failed to load resource: the server responded with a status of 403 ()
  
   Access to XMLHttpRequest at 'http://localhost:8080/save-account' 
   from origin 'http://localhost:4200' has been blocked by CORS 
   policy: Response to preflight request doesn't pass access control 
   check: No 'Access-Control-Allow-Origin' header is present on the 
   requested resource.
  
   HttpErrorResponse
       error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 
       0, total: 0, type: "error", …}
       headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, 
       headers: Map(0)}
       message: "Http failure response for (unknown url): 0 Unknown Error"
       name: "HttpErrorResponse"
       ok: false
       status: 0
       statusText: "Unknown Error"
       url: null
       __proto__: HttpResponseBase
  </code></pre>
  
  <p>Please help me to get rid of this error and explain why is it happening.
  Thanks in advance.</p>