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); }); } }

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

相关内容

热门资讯

详细透视!sohoo竞技联盟辅... 详细透视!sohoo竞技联盟辅助器,微信小程序微乐修改器,技法教程(有挂存在)-哔哩哔哩1、soho...
推荐透视!sohoo竞技联盟辅... 推荐透视!sohoo竞技联盟辅助器!竟然是真的有辅助方法(今日头条)-哔哩哔哩一、sohoo竞技联盟...
揭露透视!佛手在线是不是有挂!... 揭露透视!佛手在线是不是有挂!本来有辅助技巧(证实有挂)-哔哩哔哩;亲,关键说明,佛手在线是不是有挂...
揭露透视!wepoker怎么设... 揭露透视!wepoker怎么设置房间,淘宝的微乐辅助是真的吗,要领教程(有挂神器)-哔哩哔哩亲,关键...
专业透视!约局吧开挂!一贯一直... 专业透视!约局吧开挂!一贯一直都是有辅助神器(有挂解密)-哔哩哔哩1)约局吧开挂辅助插件:进一步探索...
了解透视!wpk显示有作弊,微... 了解透视!wpk显示有作弊,微乐家乡官方app下载,法子教程(有挂方法)-哔哩哔哩运wpk显示有作弊...
详情透视!德州之星扫描器!好像... 详情透视!德州之星扫描器!好像一直总是有辅助软件(有挂总结)-哔哩哔哩德州之星扫描器能透视中分为三种...
关于透视!竞技联盟透视,微乐自... 关于透视!竞技联盟透视,微乐自建房脚本最新版本更新内容,操作教程(有人有挂)-哔哩哔哩1、许多玩家不...
曝光透视!wepoker安装教... 曝光透视!wepoker安装教程!切实一直总是有辅助工具(真的有挂)-哔哩哔哩1、wepoker安装...
了解透视!哈糖大菠萝助手,微乐... 了解透视!哈糖大菠萝助手,微乐游戏小程序辅助器免费,模块教程(有挂方针)-哔哩哔哩;1、在哈糖大菠萝...