I’ve created a simple Rest application using Spring. When I try to enter the API using Angular I got this error
Access to XMLHttpRequest at '``http://localhost:9595/api/luoghi/all``' from origin '``http://localhost:4200``' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
How can I solve this?
These are the files:
Rest Controller
package it.ootareg.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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;
import it.ootareg.entities.Luoghi;
import it.ootareg.services.LuoghiService;
import jakarta.transaction.Transactional;
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/luoghi")
@Transactional
public class LuoghiController {
@Autowired
private LuoghiService lService;
@GetMapping("/all")
public ResponseEntity<List<Luoghi>> getAll(){
List<Luoghi> luoghi = lService.findAll();
return new ResponseEntity<>(luoghi, HttpStatus.OK);
}
@GetMapping("/find/{id}")
public ResponseEntity<Luoghi> getById(@PathVariable("id") Long id){
Luoghi luoghi = lService.findLuoghiById(id );
return new ResponseEntity<>(luoghi, HttpStatus.OK);
}
@PostMapping("/add")
public ResponseEntity<Luoghi> add(@RequestBody Luoghi luogo){
Luoghi newLuogo = lService.addLuoghi(luogo);
return new ResponseEntity<>(newLuogo, HttpStatus.CREATED);
}
@PutMapping("/update")
public ResponseEntity<Luoghi> update(@RequestBody Luoghi luogo){
Luoghi newLuogo = lService.updateLuoghi(luogo);
return new ResponseEntity<>(newLuogo, HttpStatus.OK);
}
@GetMapping("/delete/{id}")
public ResponseEntity<?> delete (@PathVariable("id") Long id){
lService.deleteLuoghi(id);
return new ResponseEntity<>(HttpStatus.OK);
}
}
Web Config
package it.ootareg.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:4200")
.allowedMethods(HttpMethod.GET.name(),
HttpMethod.POST.name(),
HttpMethod.PUT.name(),
HttpMethod.DELETE.name())
.allowedHeaders(HttpHeaders.CONTENT_TYPE,
HttpHeaders.AUTHORIZATION);
}
}
Rest Service
package it.ootareg.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import it.ootareg.entities.Luoghi;
import it.ootareg.exceptions.UserNotFoundException;
import it.ootareg.repo.LuoghiRepo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Service
public class LuoghiService {
@Autowired
private LuoghiRepo repo;
public Luoghi addLuoghi(Luoghi luogo) {
return repo.save(luogo);
}
public List<Luoghi> findAll(){
return repo.findAll();
}
public Luoghi updateLuoghi(Luoghi luogo) {
return repo.save(luogo);
}
public void deleteLuoghi(Long id) {
repo.deleteLuoghiById(id);
}
public Luoghi findLuoghiById(Long id) {
return repo.findLuoghiById(id).orElseThrow(
()->new UserNotFoundException("Luogo " + id +" non trovato"));
}
}
Angular Service
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Luoghi } from './Luoghi';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LuoghiService {
constructor(private http: HttpClient) { }
private apiUrl = "http://localhost:9595/api";
public getLuoghi() : Observable<Luoghi[]> {
return this.http.get<Luoghi[]>(`${this.apiUrl}/luoghi/all`)
}
public addLuogo(luogo : Luoghi) : Observable<Luoghi> {
return this.http.post<Luoghi>(`${this.apiUrl}/luoghi/add`, luogo)
}
public updateLuogo(luogo : Luoghi) : Observable<Luoghi> {
return this.http.put<Luoghi>(`${this.apiUrl}/luoghi/update`, luogo)
}
public deleteLuogo(luogoID : number) : Observable<void> {
return this.http.delete<void>(`${this.apiUrl}/luoghi/delete/${luogoID}`)
}
}
app module
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LuoghiService } from './luoghi.service';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [LuoghiService],
bootstrap: [AppComponent]
})
export class AppModule { }
I’ve tried these things but the error remain, what am I missing?
I’ve tried differents option that I’ve found here on Stackoverflow but none of them is working.
I’ve tried even to put the actual link in the annotation (“localhost:4200”) but neither that has worked.