Home > Mobile >  CORS origin error spring boot angular on localhost
CORS origin error spring boot angular on localhost

Time:01-11

I'm trying to consume a Restful api developed on spring boot via an Angular app and I faced this issue here is below my implementation :

  1. Spring boot controller :

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:4200/")
public class ProductController {
    @Autowired
    private ProductService productService;

    @PostMapping("/add")
    public void addProduct(@RequestBody Product p){
        productService.addProduct(p);
    }

    @GetMapping("/list")
    public List<Product> getListOfProducts(){
        return productService.getAllProducts();
    }
}

  1. Angular Service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ProductsService {

  constructor(private http: HttpClient) { }
  getProducts(){
    return this.http.get("localhost:4200/api/list");
  }
}

  1. Angular Component

import { Component, OnInit } from '@angular/core';
import { ProductsService } from '../products.service';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {

  constructor(private products:ProductsService) { }

  ngOnInit() {
    this.products.getProducts().subscribe((res)=>{
      console.warn(res);
    })
  }

}

When trying to run the angular app i face this error :

Access to XMLHttpRequest at 'localhost:4200/api/list' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

enter image description here

CodePudding user response:

@CrossOrigin(origins = "*")

check this out.

CodePudding user response:

Alternative answer. You can add to config class:

public class WebConfig implements WebMvcConfigurer {
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE")
                .allowedOrigins("*")
                .maxAge(3600);
    }
}
  •  Tags:  
  • Related