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)枫叶辅助器辅助插件:进一步探索枫叶辅助器辅助...
攻略讲解!小程序河北微乐脚本!... 攻略讲解!小程序河北微乐脚本!一直存在有辅助教程(有挂猫腻)1、小程序河北微乐脚本免费辅助多个强度级...
今年以来!潮汕潮汕娱脚本!竟然... 今年以来!潮汕潮汕娱脚本!竟然是有辅助工具(有挂神器)1、这是跨平台的潮汕潮汕娱脚本轻量版有透视,在...
现有关情况通报如下!欢乐对决手... 现有关情况通报如下!欢乐对决手游辅助!竟然真的有辅助挂(有挂规律)1、在欢乐对决手游辅助插件功能辅助...
推荐一款!情怀郴州字牌辅助!都... 推荐一款!情怀郴州字牌辅助!都是存在有辅助教程(有挂方针)情怀郴州字牌辅助透视方法中分为三种模型:情...
最新技巧!微乐家乡游戏攻略!竟... 最新技巧!微乐家乡游戏攻略!竟然确实有辅助工具(有挂详情)小薇(辅助器软件下载)致您一封信;亲爱微乐...
必备攻略!边锋老友杰克辅助!确... 必备攻略!边锋老友杰克辅助!确实真的有辅助技巧(有人有挂)亲,关键说明,边锋老友杰克辅助透视脚本安卓...
2分钟细说!微信新版518互游... 2分钟细说!微信新版518互游辅助!竟然确实有辅助神器(有挂秘诀)1、下载好微信新版518互游辅助正...