3
I am developing an integrated Java Backend (Rest Spring) with Angular Front 8. When trying to list the list of users(via JSON) I get this message:
Access to Xmlhttprequest at 'http://localhost:8080/contacts' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested Resource.
Imagery:
The repository: https://github.com/alexjosesilva/desafio-java-pl-apply
I created a config.js file to configure the proxy(front):
const proxy = [
{
context: '/api',
target: 'http://localhost:8080'
}
];
module.exports = proxy;
Code of the service.ts in which http request occurs:
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}`);
}
}
And I created a webMVCConfigureAdapter() class to enable back accesses:
@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");
}
}
I used the notes: @Crossorigin in Contactource.java for a inhabit the access to json.
However the error still persists.
Contactource.java class package com.stefanini.contacts.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();
}
}
Research
I don’t know how to solve this in Java, but CORS is a set of headers that the server sends to the client, telling which websites can access that service, with which methods, etc. So, even if another site wants to access the service, the browser refuses. The main one is "Access-Control-Allow-Origin". A quick way is to send "Access-Control-Allow-Origin: *" (asterisk) allows any client, is not ideal from a security point of view but solves the immediate problem.
– epx
Angular is a client-side framework. In Node.js, if you use Express as a server, you can try using the Cors https://expressjs.com/en/resources/middleware/cors.htmlmodule
– epx
Related: How to Configure CORS Correctly in Spring Boot?
– Icaro Martins
Related: How to release CORS to a particular address?
– Icaro Martins
Where is the project configuration file?
– emanuel cavalcante
@emanuelcavalcante on the back or front ?
– alexjosesilva
In the back........
– emanuel cavalcante
https://github.com/alexjosesilva/desafio-java-pl-apply/blob/master/backend/src/main/resources/application.properties
– alexjosesilva
created a file called: Webconfig it was described in the above code @emanuelcavalcante
– alexjosesilva