为什么在向Spring Boot后端角度发送数据时会出现此错误?

时间:2019-12-03 06:18:24

标签: angular spring spring-boot

在弹簧端子中接收到以下警告:

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 addtudent.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发布数据,它工作得很好。 但是当我尝试使用角度UI发送数据时,它不起作用,并且在spring终端中收到上述错误

2 个答案:

答案 0 :(得分:0)

由于未正确发送所需的请求正文,因此显示此错误。您的保存方法期望请求正文为Student类型。您可以在角度应用程序中创建一个FormData对象,然后在FormData对象内附加所有字段,最后在将请求发送到Spring后端时,将Formdata对象的名称绑定为Student。

答案 1 :(得分:0)

如果您说Postman工作正常,但从您的应用程序无法正常运行,则表明您在API呼叫中发送的数据有问题。

如果您使用Angular 4+标头是可选的

尝试

save(newStudent: Student) {
    return this.http.post(this.url  + 'student', JSON.stringify(newStudent) );
}

如果这不起作用,您可以检查浏览器控制台以查看“请求”中传递了什么值及其内容类型,然后在此处添加。

like this

编辑1:

尝试一下

  save(newStudent: Student) {
    return this.http.post(this.url  + 'student', JSON.stringify(newStudent), headeroption);
  }

编辑:2

基于屏幕截图,由于您在不同的端口上运行UI而Spring在不同的端口上运行,看起来就像是CORS问题

像这样创建WebMvcConfig类以允许CrossOrigin

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private final long MAX_AGE_SECS = 3600;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS").allowedHeaders("*")
                .allowCredentials(true).maxAge(MAX_AGE_SECS);
    }

}