Currently, I am in the process of developing a REST API using Spring to perform CRUD operations based on a tutorial I found. However, I have encountered an issue with the HTTP client not retrieving data, and upon inspection, I discovered the following error:
GET sockjs.js:1606 GET http://localhost:9000/sockjs-node/info?t=1626851020608 net::ERR_CONNECTION_REFUSED
I can confirm that my server is up and running, and the URL is accurate. I have also included Access-Control-Allow-Origin origin in the header. Removing this results in another error related to CORS policy denial.
Below is the code snippet from my employee.service.ts file:
import { Injectable } from '@angular/core';
import { HttpClient} from '@angular/common/http' ;
import { Observable } from 'rxjs';
import { Employee } from './employee';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
private baseUrl = "http://localhost:8080/api/v1/employees" ;
constructor(private httpClient: HttpClient) { }
getEmployeesList() : Observable<Employee[]>
{
return this.httpClient.get<Employee[]>(`${this.baseUrl}`) ;
}
}
And here is the content from my employee-list.component.ts file:
import { Component, OnInit } from '@angular/core';
import { Employee } from '../employee' ;
import { EmployeeService } from '../employee.service';
@Component({
selector: 'app-employee-list',
templateUrl: './employee-list.component.html',
styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
employees!: Employee[];
constructor(private employeeService : EmployeeService) { }
ngOnInit(): void {
this.getEmployees();
}
private getEmployees()
{
this.employeeService.getEmployeesList().subscribe(data => this.employees);
}
}
Lastly, the controller implemented in Spring Boot can be seen below:
package net.javaguides.springboot.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import net.javaguides.springboot.repository.EmployeeRepository ;
import net.javaguides.springboot.model.Employee ;
@CrossOrigin("*")
@RestController
@RequestMapping("/api/v1/")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository ;
//get all employees
@GetMapping("/employees")
public List<Employee> getAllEmployees()
{
return employeeRepository.findAll() ;
}
}
Despite multiple attempts, I continue to face issues with the GET request being denied consistently.