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、雀友会广东潮汕辅助脚本免...
一分钟教你!微信卡五星辅助器,... 一分钟教你!微信卡五星辅助器,微信超级3+1辅助,详细工具(有挂辅助)1、进入游戏-大厅左侧-新手福...
总算了解!威信茶馆app插件,... 总算了解!威信茶馆app插件,开心赢三张自建房有挂吗,详细器(有挂攻略)1、让任何用户在无需开心赢三...
实操分享!牌乐门黑科技,西元文... 实操分享!牌乐门黑科技,西元文山攻略,详细神器(有挂方式)1、完成西元文山攻略辅助器v3.3的残局,...
大家学习交流!老k麻将辅助器,... 大家学习交流!老k麻将辅助器,福建天天开心辅助软件大全,详细器(有挂头条)1、福建天天开心辅助软件大...
一分钟了解!新超凡软甲辅助,广... 一分钟了解!新超凡软甲辅助,广西友乐辅助app,详细神器(真实有挂)1、新超凡软甲辅助辅助软件下载优...
大神推荐!朋友局辅助器免费版,... 大神推荐!朋友局辅助器免费版,小程序微乐贵阳捉鸡麻将挂,详细插件(有挂教学)1、下载好小程序微乐贵阳...
一分钟了解!微乐贵阳捉鸡麻将能... 一分钟了解!微乐贵阳捉鸡麻将能不能开挂,微乐小程序辅助开发,详细软件(揭秘有挂)1、玩家可以在微乐贵...
玩家必看科普!福州十八扑外卦,... 玩家必看科普!福州十八扑外卦,雷霆辅助器,详细挂(发现有挂)福州十八扑外卦透视方法中分为三种模型:福...