繁体   English   中英

缺少所需的请求正文:在 spring 启动和 angular 9

[英]Required request body is missing:in spring boot and angular 9

我正在使用 angular 9 和 spring 启动 2。

我在 angular 9 中有一项服务 class 为:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Book } from '../common/book';
import { BookCategory } from '../common/book-category';
import { Finalcart } from '../common/finalcart';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};


@Injectable({
  providedIn: 'root'
})
export class BookService {

  private finalCart="http://localhost:8080/api/test/";

  constructor(private httpClient:HttpClient) { }


addFinalCart(finalCart:Finalcart):Observable<any>{
 return this.httpClient.post(`${this.finalCart}`+'finalCart',finalCart,httpOptions);   
}

}

在我的 spring 引导中,我将 api 暴露为:

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/test")
public class TestController {
    @PostMapping("/finalCart")
        @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')")
        public ResponseEntity<?> finalCart(@RequestBody Finalcart finalCart) {
            
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String user = auth.getName();
            
            System.out.println(user);
           System.out.println(finalCart);
        
           UserDetailsImpl userDetails=(UserDetailsImpl)userdetailService.loadUserByUsername(user);
            User u=new User(userDetails.getId(),userDetails.getUsername(),userDetails.getPassword(),userDetails.getEmail());
         Order ord= orderRep.save(new Order(u,new Date()));
             
        Billingaddress ba= billAddressRepo.save(new Billingaddress(finalCart.getBillingAddress(),ord));
        System.out.println(ba);
         
         Shippingaddress sa=shippingAddressRepo.save(new Shippingaddress(finalCart.getShippingAddress(),ord));
         System.out.println(sa);
         
         finalCart.getCartItem().forEach(s->{
             Optional<Book> b=bookrepository.findById(Long.valueOf(s.getBookId()).longValue());
            CartItem c=cartItemRepo.save(new CartItem(s.getName(),s.getImageUrl(),s.getUnitPrice(),s.getQuantity(), b.get()));
            orderDetailRepostiory.save(new OrderDetails(c,ord));    
         });
         
                if(ord!=null) {
        return  new ResponseEntity(ord, HttpStatus.OK);
            }
            else {
        return  new ResponseEntity("BadException", HttpStatus.BAD_REQUEST);
            }
            
            
        }
    }
}

所以,当我调用 api /finalCart时,我得到错误:

2020-07-05 19:57:08.187  WARN 17400 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity<?> in.ashwin.onlinebookstore.controller.TestController.finalCart(in.ashwin.onlinebookstore.entity.Finalcart)]

所以,我看到我发送的数据是: 在此处输入图像描述

因此复制了相同的 JSON 数据并尝试从 postman 发送此数据,但它正在工作。

在此处输入图像描述

I send the JSON data and there is no error when I send from postman.But,when I try to send the data using angular service class then,I get error.

我的 FinalCart.java 是:

package in.ashwin.onlinebookstore.entity;

import java.util.List;

public class Finalcart {
    
private Billingaddress  billingAddress;
private Creditcard creditCard;
private Shippingaddress shippingAddress;
private List<CartItem> cartItem;

public Billingaddress getBillingAddress() {
    return billingAddress;
}
public void setBillingAddress(Billingaddress billingAddress) {
    this.billingAddress = billingAddress;
}
public Creditcard getCreditCard() {
    return creditCard;
}
public void setCreditCard(Creditcard creditCard) {
    this.creditCard = creditCard;
}

 
@Override
public String toString() {
    return "Finalcart [billingAddress=" + billingAddress + ", creditCard=" + creditCard + ", shippingAddress="
            + shippingAddress + "]";
}
public Finalcart() {
    
}
public Shippingaddress getShippingAddress() {
    return shippingAddress;
}
public void setShippingAddress(Shippingaddress shippingAddress) {
    this.shippingAddress = shippingAddress;
}
public List<CartItem> getCartItem() {
    return cartItem;
}
public void setCartItem(List<CartItem> cartItem) {
    this.cartItem = cartItem;
}

}

book.component.ts. 当我单击提交按钮时,方法 onSubmit() 被触发。我使用 JWT 进行身份验证?我是否还需要在进行 PostMapping 时传递 JWT 令牌?

@Component({
  selector: 'app-checkout',
  templateUrl: './checkout.component.html',
  styleUrls: ['./checkout.component.css']
})
export class CheckoutComponent implements OnInit {

  cartItems: CartItem[] = [];
  totalPrice: number = 0;
  totalQuantity: number = 0;
  checkoutFormGroup: FormGroup;
   finalCart:Finalcart;

  constructor(private formBuilder: FormBuilder,private _cartService: CartService,
    private _bookService:BookService) { }

 
  ngOnInit() {
//I have not included all codes,only the required ones.
   }
  onSubmit() {
    if (this.checkoutFormGroup.invalid) {
      return;
  }
  console.log(this.cartItems);
  console.log('Purchase the books');
      let finalCart=new Finalcart(this.checkoutFormGroup.value.billingAddress,
    this.checkoutFormGroup.value.shippingAddress, this.checkoutFormGroup.value.creditCard, this.cartItems);
    
    console.log('finalcart is',finalCart);
    this._bookService.addFinalCart(this.finalCart);
  }
}

请更新 onSubmit 方法如下。 您正在方法中创建一个名为 finalCart 的新变量,但在对服务的调用中传递组件级 finalCart

onSubmit() {
    if (this.checkoutFormGroup.invalid) {
      return;
  }
  console.log(this.cartItems);
  console.log('Purchase the books');
      this.finalCart=new Finalcart(this.checkoutFormGroup.value.billingAddress,
    this.checkoutFormGroup.value.shippingAddress, this.checkoutFormGroup.value.creditCard, this.cartItems);
    
    console.log('finalcart is',this.finalCart);
    this._bookService.addFinalCart(this.finalCart);
  }

更改您的 header 选项并尝试使用text/plain

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'text/plain' })
};

因为对于请求正文,它被视为文本

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM