【发布时间】:2019-12-03 06:18:24
【问题描述】:
在春季终端收到以下警告:
WARN 7260 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public com.chamika.spire.demoapplication.Student com.chamika.spire.demoapplication.MainController.save(com.chamika.spire.demoapplication.Student)]
我的 Spring boot Maincontroller.java 代码
@RestController
public class MainController {
@Autowired
StudentService studentService;
@RequestMapping(value = "/student", method = RequestMethod.POST)
public Student save(@RequestBody Student student) {
return studentService.save(student);
}
}
我的 Angular student.service.ts 代码
import { Router } from '@angular/router';
import { Injectable } from '@angular/core';
import { Student } from '../models/student'
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
const headeroption = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class StudentService {
constructor(private http: HttpClient, private router: Router) { }
url = 'http://localhost:8080/';
student: Observable<Student[]>;
save(newStudent: Student) {
return this.http.post(this.url + 'student', newStudent, headeroption);
}
}
我的 Angular 添加student.component.ts 代码
import { Student } from './../../models/student';
import { Component, OnInit } from '@angular/core';
import { StudentService } from './../../services/student.service.service'
import { Router } from '@angular/router';
@Component({
selector: 'app-addstudent',
templateUrl: './addstudent.component.html',
styleUrls: ['./addstudent.component.scss']
})
export class AddstudentComponent implements OnInit {
student: Student = {
id: null,
firstName: '',
lastName: '',
}
constructor(private router: Router, private studentService: StudentService) { }
ngOnInit() {
this.student = {
id: null,
firstName: '',
lastName: '',
}
}
addStudent(addStu: Student) {
console.log("Went inside funtion");
console.log(this.student);
this.studentService.save(addStu).subscribe((data) => {
console.log(data);
this.ngOnInit();
});
}
}
我使用 Postman 发布数据,它运行良好。 但是当我尝试使用 Angular UI 发送数据时,它不起作用并在 spring 终端中收到上述错误
【问题讨论】:
-
请添加从 UI 传递的学生对象和 JSON。
-
好的,我添加了代码
-
console.log(this.student) 的输出是什么;还将此输出与 Postman 中传递的 JSON 进行比较,您可以检查浏览器控制台以查看正在传递的 API。 Ctrl + Shift + I 用于窗口
-
你得到的实际错误是什么?
-
@MyTwoCents 控制台输出为:Object { id: "11", firstName: "TestFname", lastName: "TestLname" }
标签: angular spring spring-boot