Angular提交的表单在Spring Boot中显示为空
创始人
2024-10-29 18:00:42
0

在Angular中提交的表单数据在Spring Boot中显示为空的问题可能有多个原因。以下是一些可能的解决方法:

  1. 确保Angular中的表单数据正确地绑定到表单控件上,并在提交时正确地传递给后端。确保表单的ngSubmit事件处理程序正确地处理表单数据,并使用HttpClient将数据发送到后端。例如:

Angular组件:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-form',
  template: `
    
`, }) export class FormComponent { formData = { name: '' }; constructor(private http: HttpClient) {} submitForm() { this.http.post('/api/submit-form', this.formData).subscribe(response => { console.log(response); }); } }
  1. 在Spring Boot中,确保后端的Controller正确地接收并处理来自Angular的表单数据。使用@RequestBody注解将请求体映射到后端的Java对象中。例如:

Spring Boot Controller:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FormController {

  @PostMapping("/api/submit-form")
  public void submitForm(@RequestBody FormData formData) {
    System.out.println(formData.getName());
    // 处理表单数据
  }
}

public class FormData {
  private String name;

  // 省略getter和setter方法
}
  1. 确保Angular和Spring Boot的跨域配置正确设置。在Spring Boot中,可以使用@CrossOrigin注解来允许来自Angular的跨域请求。在Angular中,可以使用HttpClient的withCredentials选项来处理跨域请求。例如:

Spring Boot Controller:

import org.springframework.web.bind.annotation.CrossOrigin;

@RestController
public class FormController {

  @CrossOrigin(origins = "http://angular-app-url")
  @PostMapping("/api/submit-form")
  public void submitForm(@RequestBody FormData formData) {
    // 处理表单数据
  }
}

Angular组件:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-form',
  template: `
    
`, }) export class FormComponent { formData = { name: '' }; constructor(private http: HttpClient) {} submitForm() { this.http.post('/api/submit-form', this.formData, { withCredentials: true }).subscribe(response => { console.log(response); }); } }

以上是一些可能的解决方法,但具体解决方法可能因具体情况而异。您可以根据您的代码和需求进行调整和修改。

相关内容

热门资讯

据公告内容!如何下载安装胡乐辅... 据公告内容!如何下载安装胡乐辅助脚本!切实真的是有辅助器(有挂秘笈)-哔哩哔哩1、金币登录送、破产送...
针对!越乡游义乌微信小程序辅助... 针对!越乡游义乌微信小程序辅助!总是有挂辅助神器(确实有挂)-哔哩哔哩1、进入到越乡游义乌微信小程序...
这一问题亟待解决!黑科技软件大... 这一问题亟待解决!黑科技软件大全!本来真的有辅助软件(有挂辅助)-哔哩哔哩进入游戏-大厅左侧-新手福...
备受关注的!拱趴大菠萝系统规律... 备受关注的!拱趴大菠萝系统规律!确实是真的辅助修改器(有挂技巧)-哔哩哔哩1、用户打开应用后不用登录...
突发!战皇大厅辅助那个可靠!原... 突发!战皇大厅辅助那个可靠!原来真的是有辅助挂(有挂头条)-哔哩哔哩所有人都在同一条线上,像星星一样...
近年来!手机科乐辅助!原来真的... 您好,手机科乐辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家在...
据报道!南宁友乐辅助!切实真的... 据报道!南宁友乐辅助!切实真的有辅助神器(有挂教程)-哔哩哔哩1)南宁友乐辅助免费钻石:进一步探索南...
据监测!佛手十三道辅助!果然是... 据监测!佛手十三道辅助!果然是有辅助挂(有挂讲解)-哔哩哔哩1、每一步都需要思考,不同水平的挑战会更...
今天下午!奇迹陕西游戏辅助器!... 今天下午!奇迹陕西游戏辅助器!其实是真的辅助挂(存在有挂)-哔哩哔哩1、上手简单,内置详细流程视频教...
做出回应!衢州多莱辅助器!切实... 做出回应!衢州多莱辅助器!切实真的是有辅助安装(真的有挂)-哔哩哔哩1、全新机制【衢州多莱辅助器ai...