Estou desenvolvendo uma Backend em Java(Rest Spring) integrado com Front em Angular 8. Ao tentar listar o a lista de usuarios(via JSON) recebo essa mensagem:
Access to XMLHttpRequest at 'http://localhost:8080/contatos' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Imagem:
O repositório: https://github.com/alexjosesilva/desafio-java-pl-apply
Criei um arquivo config.js para configurar a proxy(front):
const proxy = [
{
context: '/api',
target: 'http://localhost:8080'
}
];
module.exports = proxy;
Codigo do service.ts no qual ocorre a requisição http:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
private baseUrl = 'http://localhost:8080/contatos';
constructor(private http: HttpClient) { }
getUser(id: number): Observable<any> {
return this.http.get(`${this.baseUrl}/${id}`);
}
createUser(user: Object): Observable<Object> {
return this.http.post(`${this.baseUrl}`, user);
}
updateUser(id: number, value: any): Observable<Object> {
return this.http.put(`${this.baseUrl}/${id}`, value);
}
deleteUser(id: number): Observable<any> {
return this.http.delete(`${this.baseUrl}/${id}`, { responseType: 'text' });
}
getUserList(): Observable<any> {
return this.http.get(`${this.baseUrl}`);
}
}
E criei uma classe webMVCConfigureAdapter() para habilitar os acessos ao back:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedHeaders("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "TRACE", "CONNECT");
}
}
Usei as anotações: @CrossOrigin na classe ContatoResource.java afim de a habitar o acesso ao json.
Contudo o erro ainda persiste.
Classe ContatoResource.java package com.stefanini.contatos.resource;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
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;
import com.stefanini.contatos.model.Contato;
import com.stefanini.contatos.repository.Contatos;
@RestController
@RequestMapping("/contatos")
public class ContatosResource {
@Autowired
private Contatos contatos;
@PostMapping
public Contato adicionar(@Valid @RequestBody Contato contato) {
return contatos.save(contato);
}
@CrossOrigin
@GetMapping
public List<Contato> listar() {
return contatos.findAll();
}
@GetMapping("/{id}")
public ResponseEntity<Contato> buscar(@PathVariable Long id) {
Contato contato = contatos.findOne(id);
if (contato == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(contato);
}
@PutMapping("/{id}")
public ResponseEntity<Contato> atualizar(@PathVariable Long id,
@Valid @RequestBody Contato contato) {
Contato existente = contatos.findOne(id);
if (existente == null) {
return ResponseEntity.notFound().build();
}
BeanUtils.copyProperties(contato, existente, "id");
existente = contatos.save(existente);
return ResponseEntity.ok(existente);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> remover(@PathVariable Long id) {
Contato contato = contatos.findOne(id);
if (contato == null) {
return ResponseEntity.notFound().build();
}
contatos.delete(contato);
return ResponseEntity.noContent().build();
}
}
Pesquisas