如何从Angular向Spring Boot发送请求体参数(无需请求头)
前端请求调整与后端代码实现方案
一、Angular前端请求调整
方式1:封装为JSON对象发送(推荐)
直接传纯字符串的请求体不符合REST接口的常规设计,建议把学号封装成JSON对象发送,这样后端更易处理,也便于后续扩展参数:
login() { // 键名`studentId`要和后端模型类的属性名完全匹配 const body = { studentId: "091" }; return this.http.post("http://localhost/api/users/login", body); }
发送的请求体格式为:{"studentId":"091"},Spring Boot可以自动绑定到模型类。
方式2:直接发送纯字符串(仅兼容场景)
如果一定要直接传字符串"091",必须手动设置请求头的Content-Type为text/plain,否则Spring Boot会按JSON格式解析导致报错:
import { HttpHeaders } from '@angular/common/http'; login() { const body = "091"; const headers = new HttpHeaders().set('Content-Type', 'text/plain'); return this.http.post("http://localhost/api/users/login", body, { headers }); }
二、Spring Boot后端代码实现
情况1:接收封装的JSON对象(对应前端方式1)
1. 模型类(Login.java)
定义与前端对象键名一致的属性,推荐用Lombok的@Data注解自动生成getter/setter,简化代码:
import lombok.Data; @Data public class Login { // 属性名和前端的`studentId`完全一致 private String studentId; }
如果不用Lombok,手动编写getter/setter:
public class Login { private String studentId; public Login() {} public String getStudentId() { return studentId; } public void setStudentId(String studentId) { this.studentId = studentId; } }
2. 控制器代码
修正控制器的请求路径(要和前端请求的/api/users/login完全匹配),通过@RequestBody绑定请求体到模型类:
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @PostMapping("/api/users/login") public String handleLogin(@RequestBody Login login) { // 获取前端传来的学号 String studentId = login.getStudentId(); // 这里添加你的登录验证逻辑 return "登录成功,学号:" + studentId; } }
情况2:接收纯字符串(对应前端方式2)
如果前端直接传字符串,控制器可以直接用@RequestBody String接收,无需模型类:
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @PostMapping("/api/users/login") public String handleLogin(@RequestBody String studentId) { // 直接拿到学号"091" return "登录成功,学号:" + studentId; } }
注意:这种方式必须配合前端设置Content-Type: text/plain,否则会抛出JSON解析异常。
内容的提问来源于stack exchange,提问作者anonymousowl
相关产品推荐
相关产品推荐

