在 Spring Boot 中从 Angular 向后端发送 post 请求中的对象的问题

Posted

技术标签:

【中文标题】在 Spring Boot 中从 Angular 向后端发送 post 请求中的对象的问题【英文标题】:problem with sending object in post request from angular to backend in springboot 【发布时间】:2021-12-26 23:55:43 【问题描述】:

当我尝试将 post 请求从 Angular 发送到 Spring Boot 时遇到问题。我必须面对 404 Not Found 错误。这是我的角度服务代码:

import  DonatorDTO  from '../models/donatorDTO';
import  HttpHeaders, HttpClient  from "@angular/common/http";
import  Injectable  from '@angular/core';
import  BehaviorSubject, Observable  from 'rxjs';

@Injectable(
    providedIn: 'root'
)
export class DonatorsService 
    private watKrewDonationUrl = "http://localhost:8080/donators";

    constructor(private _http: HttpClient)

    public addDonator(donatorDTO: DonatorDTO): Observable<DonatorDTO>
        return this._http.post<DonatorDTO>(this.watKrewDonationUrl, donatorDTO);
    

这里是角度组件代码:

import  DonatorDTO  from './../../models/donatorDTO';

import  DonatorsService  from './../../services/donators.service';
import  Component, OnInit  from '@angular/core';
import  FormBuilder, FormControl, FormGroup, NgForm, Validators  from '@angular/forms';

@Component(
  selector: 'app-donators',
  templateUrl: './donators.component.html',
  styleUrls: ['./donators.component.css']
)
export class DonatorsComponent implements OnInit 

  donatorForm: NgForm;

  constructor(private donatorService: DonatorsService) 
  ngOnInit(): void 

  

  donatorDTO: DonatorDTO = new DonatorDTO();
  companies: string [] =['1. kompania','2. kompania','3. kompania','4. kompania','5. kompania','6. kompania','7. kompania','8. kompania',
                        '9. kompania','10. kompania','11. kompania','12. kompania','13. kompania','14. kompania','15. kompania','16. kompania',
                        '17. kompania','18. kompania','19. kompania','20. kompania','21. kompania'];
  bloodGroups: string [] = ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', '0+', '0-'];
  ranks: string [] = ['szer. pchor.', 'st. szer. pchor.', 'kpr. pchor.', 'st. kpr. pchor.', 'plut. pchor.', 'sierż. pchor.'];

  createDonator() 
    console.log(this.donatorDTO);
    this.donatorService.addDonator(this.donatorDTO).subscribe(data => 
      console.log(data)
    )
  
  

这是.html代码

<!DOCTYPE html>
<html lang="pl-PL">
<body>
    <div class="container">
        <div class="col-md-6">
            <form #donatorForm="ngForm" (ngSubmit) = "createDonator()" >
                <div class="form-group">
                    <input type="text" class = "form-control" [(ngModel)]="donatorDTO.name"  name="name" placeholder="np. Jan"  >
                    <small id="nameHelp" class="form-text text-muted">Podaj imię dawcy</small>
                </div>
                <div class="form-group">
                    <input type="text" class = "form-control" [(ngModel)]="donatorDTO.surname"  name="surname" placeholder="np. Kowalski"  >
                    <small id="surnameHelp" class="form-text text-muted">Podaj nazwisko dawcy</small>
                </div>
                <div class="form-group">
                    <input type="email" class = "form-control" [(ngModel)]="donatorDTO.email"  name="email" placeholder="np. jan.kowalski@wp.pl" >
                    <small id="emailHelp" class="form-text text-muted">Podaj email na którego dawca będzie otrzymywał wiadomości związane z HDK</small>
                </div>
                <div class="form-group">
               <select class="form-control" [(ngModel)]="donatorDTO.militaryRank" name="militaryRank">
                   <option *ngFor="let rank of ranks" [ngValue]="rank">rank</option>
               </select>
                <small id="rankHelp" class="form-text text-muted">Podaj stopień wojskowy</small>
                </div>
                <div class="form-group">
                <select [(ngModel)]="donatorDTO.companyName"  name="company" >
                    <option *ngFor="let cmp of companies" [ngValue]="cmp">cmp</option>
                </select>
                <small id="companyHelp" class="form-text text-muted">Wybierz pododdział dawcy</small>
                </div>
                <div class="form-group">
                    <select [(ngModel)]="donatorDTO.bloodGroup" name="bloodGroup" >
                        <option *ngFor="let blood of bloodGroups" [ngValue]="blood">blood</option>
                    </select>
                </div>
                <div class="form-group">
                    <button class = "btn btn-success"  type="submit">Dodaj dawcę do bazy</button>
                </div>
            </form>
            
        </div>
    </div>
</body>
</html>

这是模型组件:

export class DonatorDTO 
    name: string;
    surname: string;
    email: string;
    militaryRank: string;
    companyName: string;
    bloodGroup: string;

现在是springboot服务代码:

public void addDonator(DonatorDTO donatorDTO) throws MailException 
        if (donatorRepository.existsByEmail(donatorDTO.getEmail())) 
            throw new RuntimeException("User with this e-mail already exists in db");
         else 
            Donator donator = new Donator();
            Company company = companyRepository.findByCompanyName(donatorDTO.getCompanyName()).orElseThrow(() -> new ResourceNotFoundException("Company not found"));
            BloodGroup blood = bloodGroupRepository.findBloodGroupByBloodType(donatorDTO.getBloodGroup()).orElseThrow(() -> new ResourceNotFoundException("Blood group not found"));
            donator.setName(firstLetterToUpperCase(donatorDTO.getName()));
            donator.setSurname(firstLetterToUpperCase(donatorDTO.getSurname()));
            donator.setEmail(donatorDTO.getEmail());
            donator.setMilitaryRank(donatorDTO.getMilitaryRank());
            donator.setCompany(company);
            donator.setBloodGroup(blood);
            blood.setNumberOfDonators(blood.getNumberOfDonators() + 1);
            donator.setNextDonationDate(LocalDate.now());
            donator.setIsCapable(true);
            donatorRepository.save(donator);
            try 
                mailService.helloNotification(donatorDTO);
             catch (MailException mailException) 
                logger.error("Can't send email with confirmation of addition donator in a database");
                logger.error(mailException.getMessage());
             catch (UnsupportedEncodingException e) 
                e.printStackTrace();
             catch (MessagingException e) 
                e.printStackTrace();
            
        
    

和控制器代码:

@RestController
public class DonatorController 

    @Autowired
    private final DonatorService donatorService;
    private final MailService mailService;

    public DonatorController(DonatorService donatorService, MailService mailService) 
        this.donatorService = donatorService;
        this.mailService = mailService;
    

    @PostMapping(value = "donators")
    public ResponseEntity addDonator(@RequestBody DonatorDTO donatorDTO) 
        donatorService.addDonator(donatorDTO);
        return new ResponseEntity<>(HttpStatus.OK);
    

如果有人解决我的问题,我将不胜感激

【问题讨论】:

【参考方案1】:

在我看来你的@PostMapping 值不对,试试@PostMapping(value = "/donators") 如下:

@RestController
public class DonatorController 

    private final DonatorService donatorService;
    private final MailService mailService;

    public DonatorController(DonatorService donatorService, MailService mailService) 
        this.donatorService = donatorService;
        this.mailService = mailService;
    

    @PostMapping(value = "/donators")
    public ResponseEntity addDonator(@RequestBody DonatorDTO donatorDTO) 
        donatorService.addDonator(donatorDTO);
        return new ResponseEntity<>(HttpStatus.OK);
    

【讨论】:

不幸的是,我按照您的建议更改后仍然是同样的问题 那您可以分享一下您调用端点时您的Spring Boot应用程序的日志吗?例如,您是否尝试将其称为 Postman? 我尝试使用 swagger 调用端点,然后一切正常。在数据库中创建了新的捐赠者。问题只是当我尝试从角度添加对象时 那么问题出在角码本身,我帮不了你,对不起。

以上是关于在 Spring Boot 中从 Angular 向后端发送 post 请求中的对象的问题的主要内容,如果未能解决你的问题,请参考以下文章

在 Eclipse 中从 Spring:boot 项目创建 war 文件

如何在 Spring Boot 中从控制器覆盖 @JsonInclude

在 Spring Boot 中从 JWT 安全检查中排除 URL

如何在apache中从角度调用spring boot api

在 Spring Boot 中从 jwt 获取附加属性

在 CircleCi 中从 Spring Boot 访问 PostgreSQL 9.6