【发布时间】:2021-09-28 13:55:51
【问题描述】:
我正在使用 spring 制作一个 rest API,它可以按照教程进行 crud 操作。但是 HTTP 客户端没有获取数据,在检查时我得到了错误
GET sockjs.js:1606 GET http://localhost:9000/sockjs-node/info?t=1626851020608 net::ERR_CONNECTION_REFUSED
我知道我的服务器正在运行并且链接正确。 我在标题中提供了 Access-Control-Allow-Origin 来源,如果我删除它,我会收到另一个错误 cros policy denied 。
这是我的employee.service.ts
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}`) ;
}
}
下面是我的员工列表.component.ts
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);
}
}
这是我在 Spring Boot 中的控制器
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() ;
}
}
我尝试了很多次,但每次get请求都被拒绝。
【问题讨论】:
-
欢迎来到 SO 社区,Aastha Singh!您很好地提供了该问题的所有信息。我不明白为什么有人投了反对票 :( 无论如何,完成介绍性之旅stackoverflow.com/tour 对您和社区都是有益的。它有助于了解要提供哪些信息以及如何提出问题以有更好的机会寻求帮助。并且会给你一个徽章(:
标签: angular typescript spring-boot jpa rest