Angular:Http删除在我的rest api全栈项目中不起作用

Posted

技术标签:

【中文标题】Angular:Http删除在我的rest api全栈项目中不起作用【英文标题】:Angular: Http delete is not working in my rest api full stack project 【发布时间】:2021-09-29 14:10:17 【问题描述】:

我正在使用 spring 制作一个 rest API 来执行 crud 操作。 在我的 Angular 应用程序中,删除 HTTP 客户端不起作用,当我单击删除按钮时,选定的 id 不会被删除。 我知道我的服务器正在运行并且控制器代码是正确的。

这是 Employee-list.component.ts

import  Component, OnInit  from '@angular/core';
import  Router  from '@angular/router';
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 ,
    private router : Router)  

  ngOnInit(): void 

      this.fetchEmployees();
  
  private fetchEmployees()
  
    
    this.employeeService.getEmployeesList().subscribe(data => this.employees = data );
  

  updateEmployee(id : number)
  
    this.router.navigate(['update-employee' , id ]) ;
  
  deleteEmployee(id : number)
  
    this.employeeService.deleteEmployee(id).subscribe(data => 
      
      this.fetchEmployees() ;
    )
  



这是服务页面 - employee.service.ts

import  Injectable  from '@angular/core';
import  HttpClient from '@angular/common/http' ;
import  Observable  from 'rxjs';
import  Employee  from './employee';

/** Injectable - means it will be used to provide services  */
@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`) ; 
     
   

   createEmployee(employee : Employee) : Observable<Object>
     return this.httpClient.post(`$this.baseUrl` , employee) ;
    

   
  getEmployeeById(id: number): Observable<Employee>
    return this.httpClient.get<Employee>(`$this.baseUrl/$id`);
  
   updateEmployee(id: number, employee: Employee): Observable<Object>
    return this.httpClient.put(`$this.baseUrl/$id`, employee);
  

  deleteEmployee(id:number ) : Observable<Object>
    return this.httpClient.delete(`$this.baseUrl/$id` ) ;
  

这里是按钮如何绑定到employee-list.component.html中的deleteEmployee()

  <button (click) = "deleteEmployee(employee.id)" class = "btn btn-danger" style="margin-left: 10px"> Delete</button>

错误是

CORS 政策已阻止从源“http://localhost:4200”访问“http://localhost:8080/api/v1/employees/1”处的 XMLHttpRequest:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

zone.js:2863 删除 http://localhost:8080/api/v1/employees/1 net::ERR_FAILED

但是我已经添加了跨域,可以很好地用于获取、发布和放置请求。请帮助。

这是 EmployeeController

package net.javaguides.springboot.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 net.javaguides.springboot.repository.EmployeeRepository ;
import net.javaguides.springboot.exception.ResourceNotFoundException;
import net.javaguides.springboot.model.Employee ;

@CrossOrigin(origins = "http://localhost:4200") 
@RestController
@RequestMapping("/api/v1/")
public class EmployeeController 
    
    
    @Autowired
    private EmployeeRepository  employeeRepository ;
    
    //get all employees
    @GetMapping("/employees")
    public List<Employee> getAllEmployees()
    
        return employeeRepository.findAll() ;
    
    
    //create employee api 
    @PostMapping("/employees")
    public Employee createEmployee(@RequestBody Employee employee)
    
        return employeeRepository.save(employee);
    
    
    // get employee by id rest api
    @GetMapping("/employees/id")
    public ResponseEntity<Employee> getEmployeeById(@PathVariable Long id) 
    
        
        Employee employee = employeeRepository
                            .findById(id)
                            .orElseThrow(()-> new ResourceNotFoundException("Employee not exist with id : " + id));
        
        return ResponseEntity.ok(employee) ;
    
    
    //update employee rest api
    @PutMapping("/employees/id")
    public ResponseEntity<Employee> updateEmployee(@PathVariable Long id ,@RequestBody Employee empdetails)
    
        Employee employee = employeeRepository
                .findById(id)
                .orElseThrow(()-> new ResourceNotFoundException("Employee not exist with id : " + id));
    employee.setFirstName(empdetails.getFirstName());
    employee.setLastName(empdetails.getLastName());
    employee.setEmailId(empdetails.getEmailId());
    
    Employee updatedEmployee =employeeRepository.save(employee);
    return ResponseEntity.ok(updatedEmployee) ;
    
    
    //delete employee rest api
    @DeleteMapping("/employees/id")
    public ResponseEntity<Map<String, Boolean>> deleteEmployee(@PathVariable Long id ,@RequestBody Employee empdetails)
    
        Employee employee = employeeRepository
                .findById(id)
                .orElseThrow(()-> new ResourceNotFoundException("Employee not exist with id : " + id));
        
        employeeRepository.delete(employee);
        Map<String, Boolean> response = new HashMap<>();
        response.put("deleted", Boolean.TRUE);
        return ResponseEntity.ok(response);
    


感谢您的帮助。我从昨天开始就卡在这部分了。

【问题讨论】:

你需要显示employee-list.component.html的内容。目前无法知道模板中的按钮是如何绑定到deleteEmployee() 函数的。 当您查看浏览器开发控制台的网络选项卡时,服务器对DELETE 请求的回答是什么? " 我已经添加了跨域适用于 get 、 post 和 put 请求" 但是你正在做一个DELETE ... 我是新手,所以我不明白在春季启动中将服务器配置放在哪里。我已将跨域放在我的控制器文件中。我会和你分享。我是新人所以请不要评判。 “我是新手,所以请不要评判”我们都曾有过这样的经历。别担心 :) 问题似乎是双重的:1)您似乎在DELETE 处理程序的映射中缺少,这可能意味着永远不会到达被调用地址2)似乎Spring Boot 需要附加配置以使用正确的 CORS 标头返回错误消息,这就是为什么您在此处收到 CORS 错误而不是 404 - 请参阅此处了解如何解决该问题:***.com/questions/35091524/… 【参考方案1】:

问题是,您的 Rest API(Java) 需要一个请求正文,而您的客户端(Angular 代码)没有发送。

更改其中一项

    controller 签名中删除@RequestBody Employee empdetails,如下所示。
//delete employee rest api
@DeleteMapping("/employees/id")
public ResponseEntity<Map<String, Boolean>> deleteEmployee(@PathVariable Long id)
    或者像这样在http delete的请求正文中添加员工详细信息
deleteEmployee(id:number, employee : Employee) : Observable<Object> 
    return this.httpClient.delete(`$this.baseUrl/$id`, employee);


【讨论】:

【参考方案2】:

使用配置文件添加新包,解决跨源错误

package net.javaguides.springboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class Myconfiguration 

    @SuppressWarnings("deprecation")
    @Bean
    public WebMvcConfigurer corsConfigurer() 
        return new WebMvcConfigurerAdapter() 
            @Override
            public void addCorsMappings(CorsRegistry registry) 
                registry.addMapping("/**")
                .allowedMethods("GET" ,"POST" , "UPDATE" ,"PUT", "DELETE")
                .allowedOrigins("*")
                .allowedHeaders("*");
            
        ;
    

我还从控制器中删除了@RequestBody Employee empdetails。

谢谢大家。它的工作。

【讨论】:

以上是关于Angular:Http删除在我的rest api全栈项目中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

显示rest api json响应,如使用angular js的文本框自动填充

使用 angular 2 的 http rest api

Laravel Rest API Google Auth 在 Angular

从 Angular 中的 REST API 获取 HTTPS 时出错

REST API、删除请求、CORS 规范或查询错误?

Ionic2,Angular2:如何在使用 http get 进行 REST API 服务调用时避免 CORS 问题?