Estoy haciendo un proyecto con angular + spring boot. Y me da el error: Failed to load resource: net::ERR_CONNECTION_REFUSED. A veces me sale este otro error: GET http://localhost:8090/api/employees net::ERR_CONNECTION_REFUSED, Dependiendo de si inicio angular con ng serve --proxy-config proxy.conf.json o con ng serve a secas.
Mi controlador de Spring boot es el siguiente.
package com.test.mainApp.controller;
import com.test.mainApp.entity.Employee;
import com.test.mainApp.repository.EmployeeRepository;
import java.util.List;
import java.util.Optional;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@CrossOrigin(origins = "http://localhost:4200", allowedHeaders="*")
@RestController
@RequestMapping("/api")
public class EmployeeController {
EmployeeRepository employeeRepository;
//@RequestMapping(value="/employees", method=RequestMethod.GET)
@GetMapping("/employees")
public List<Employee> getEmployees(){
return (List)employeeRepository.findAll();
}
//@RequestMapping(value = "/employees/{job}", method=RequestMethod.GET)
@GetMapping("/employees/{job}")
public List<Employee> getEmployeesByJob(@PathVariable String job){
return (List)employeeRepository.findByJob(job);
}
//@RequestMapping(value="/employees/{id}", method=RequestMethod.DELETE)
@DeleteMapping("/emloyees/{id}")
public boolean deleteEmployee(@PathVariable Long id){
Optional<Employee> dbEmployee = employeeRepository.findById(id);
if(dbEmployee.isPresent()) {
Employee existingEmployee = dbEmployee.get();
employeeRepository.delete(existingEmployee);
return true;
}
return false;
}
}
Mi componente para listar los empleados es este:
import { Component, OnInit } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { Employee } from '../../entities/employee';
import { EmployeeServiceService } from '../../services/employee-service.service';
@Component({
selector: 'app-list-employee',
templateUrl: './list-employee.component.html',
styleUrls: ['./list-employee.component.css']
})
export class ListEmployeeComponent implements OnInit {
employees: Array<Employee>;
constructor(private emploService: EmployeeServiceService) { }
ngOnInit() {
this.emploService.getAllEmployees()
.subscribe(response => this.employees = response), (err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log("Client-side error occured.");
} else {
console.log("Server-side error occured.");
}
});
}
}
Mi Servicio de angular es este:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { Employee } from '../entities/employee';
@Injectable({
providedIn: 'root'
})
export class EmployeeServiceService {
private url:string="http://localhost:8090/api";
constructor(private http: HttpClient) {
}
public getAllEmployees(): Observable<any> {
return this.http.get(this.url+"/employees");
}
}
Añadir que tengo el proyecto de angular dentro de ~/NetBeansProjects/MyFirstApp/src/main/resources/static/crud-employees-client (Sí, estoy en Linux. Point Linux, más concretamente). Con Spring Initializr he añadido las dependencias Web, JPA y H2. En consola, también me aparece "Server-side error occured.", que es el error que he capturado y he obtenido información gracias al HttpErrorResponse.
Si necesitáis algún dato más, decid. Gracias de antemano.
Edit:
El error es: GET http://localhost:8090/api/employees net::ERR_CONNECTION_REFUSED scheduleTask @ zone.js:2969 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:407 onScheduleTask @ zone.js:297 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:401 push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232 push../node_modules/zone.js/dist/zone.js.Zone.scheduleMacroTask @ zone.js:255 scheduleMacroTaskWithCurrentZone @ zone.js:1114 (anonymous) @ zone.js:3001 proto.(anonymous function) @ zone.js:1394 (anonymous) @ http.js:1639 push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe @ Observable.js:42 push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:28 (anonymous) @ subscribeTo.js:21 subscribeToResult @ subscribeToResult.js:6 push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._innerSub @ mergeMap.js:70 push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._tryNext @ mergeMap.js:67 push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._next @ mergeMap.js:50 push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:54 (anonymous) @ scalar.js:5 push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe @ Observable.js:42 push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:28 push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapOperator.call @ mergeMap.js:28 push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:23 push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterOperator.call @ filter.js:15 push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:23 push../node_modules/rxjs/_esm5/internal/operators/map.js.MapOperator.call @ map.js:18 push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:23 push../src/app/components/list-employee/list-employee.component.ts.ListEmployeeComponent.ngOnInit @ list-employee.component.ts:20 checkAndUpdateDirectiveInline @ core.js:9248 checkAndUpdateNodeInline @ core.js:10512 checkAndUpdateNode @ core.js:10474 debugCheckAndUpdateNode @ core.js:11107 debugCheckDirectivesFn @ core.js:11067 (anonymous) @ ListEmployeeComponent_Host.ngfactory.js [sm]:1 debugUpdateDirectives @ core.js:11059 checkAndUpdateView @ core.js:10456 callViewAction @ core.js:10697 execEmbeddedViewsAction @ core.js:10660 checkAndUpdateView @ core.js:10457 callViewAction @ core.js:10697 execComponentViewsAction @ core.js:10639 checkAndUpdateView @ core.js:10462 callWithDebugContext @ core.js:11349 debugCheckAndUpdateView @ core.js:11027 push../node_modules/@angular/core/fesm5/core.js.ViewRef_.detectChanges @ core.js:8843 (anonymous) @ core.js:4579 push../node_modules/@angular/core/fesm5/core.js.ApplicationRef.tick @ core.js:4579 (anonymous) @ core.js:4471 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388 onInvoke @ core.js:3822 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:387 push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138 push../node_modules/@angular/core/fesm5/core.js.NgZone.run @ core.js:3736 next @ core.js:4471 schedulerFn @ core.js:3553 push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:195 push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:133 push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:77 push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:54 push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47 push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3537 checkStable @ core.js:3791 onHasTask @ core.js:3835 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.hasTask @ zone.js:441 push../node_modules/zone.js/dist/zone.js.ZoneDelegate._updateTaskCount @ zone.js:461 push../node_modules/zone.js/dist/zone.js.Zone._updateTaskCount @ zone.js:285 push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:205 drainMicroTaskQueue
Edit2: Estoy en otro PC, lo he probado y he conseguido que sólo el Spring Boot me imprima Hello world, en http://localhost:8080/api/test. Pero cuando lo combino con Angular y éste tiene que obtener los datos del servidor, falla. Me sale en firefox: Solicitud de origen cruzado bloqueada: La misma política de origen no permite la lectura de recursos remotos en http://localhost:8080/api/test. (Razón: Solicitud CORS sin éxito). Y en Chrome me sigue saliendo el mismo error: Failed to load resource: net::ERR_CONNECTION_REFUSED Y se supone que añadiendo @CrossOrigin(origins="http://localhost:4200") encima del controlador debería ir, pero no es así.
Edit3: He creado una clase para evitar el problema con CORS. La clase es la siguiente:
package com.test.mainApp.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class AppConfig implements WebMvcConfigurer {
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/test").allowedOrigins("http://localhost:4200")
.allowedMethods("GET", "POST", "OPTIONS", "PUT")
.allowedHeaders("*")
.allowCredentials(true).maxAge(3600);
}
}
Ahora me sale en firefox:
Object { headers: Object, status: 0, statusText: "Unknown Error", url: null, ok: false, name: "HttpErrorResponse", message: "Http failure response for (unknown …", error: error }
Y en chromium: "Error HttpErrorResponse", aparte del "Failed to load resource: net::ERR_CONNECTION_REFUSED." Y en chromium: "Error HttpErrorResponse", aparte del "Failed to load resource: net::ERR_CONNECTION_REFUSED."
Cuando printo el error en formato string, me aparece [ object Object ]