【问题标题】:Why this error coming when angular send data to spring boot backend?为什么当 Angular 将数据发送到 Spring Boot 后端时会出现此错误?
【发布时间】: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


【解决方案1】:

如果您说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

根据屏幕截图看起来像 CORS 问题,因为您在不同的端口上运行 UI,而 Spring 在不同的端口上运行

像这样创建一个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);
    }

}

【讨论】:

  • 在没有标头的情况下收到错误:" org.springframework.web.HttpMediaTypeNotSupportedException: 不支持内容类型'text/plain;charset=UTF-8'"
  • 收到错误,标头“相同的先前错误(缺少所需的请求正文)”
  • 这是我的浏览器控制窗口“imgur.com/6yRHnBm
  • 如何将此 WebMvcConfig 文件添加到 Java Jax-rs(jersy) 程序以允许 CroosOrigin ?
【解决方案2】:

显示此错误是因为您没有正确发送所需的请求正文。您的保存方法需要具有 Student 类型的请求正文。您可以在 Angular 应用程序中创建一个 FormData 对象,然后将所有字段附加到 FormData 对象中,最后在向 spring 后端发送请求时将 Formdata 对象名称绑定为学生。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 2021-01-25
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    相关资源
    最近更新 更多