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

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

相关内容

热门资讯

透视安装!安装不了wepoke... 透视安装!安装不了wepoker(透视)逗娱科技碰胡辅助(都是存在有辅助辅助器)-哔哩哔哩1、全新机...
透视诀窍!pokemmo辅助工... 透视诀窍!pokemmo辅助工具(透视)fishpoker透视(辅助)竟然一直总是有插件(哔哩哔哩)...
现场直击!hhpoker可以控... 现场直击!hhpoker可以控制牌吗(透视)多乐跑小程序如何开辅助(本来是真的辅助安装)-哔哩哔哩1...
透视方式!哈糖大菠萝攻略(透视... 透视方式!哈糖大菠萝攻略(透视)约局吧作必弊脚本(辅助)确实有攻略(哔哩哔哩)1、超多福利:超高返利...
网友热议!wepoker私人局... 您好,上饶辅助工具这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在...
透视积累!智星菠萝可以辅助吗(... 透视积累!智星菠萝可以辅助吗(透视)拱趴大菠萝自动计算机器人(辅助)竟然存在有神器(哔哩哔哩)1、下...
透视黑科技!wepoker透视... 透视黑科技!wepoker透视辅助下载(透视)道游拼十辅助器(都是真的有辅助修改器)-哔哩哔哩1、首...
透视大纲!pokerworld... 透视大纲!pokerworld软件(透视)德州辅助工具到底怎么样(辅助)切实一直都是有软件(哔哩哔哩...
透视讲解!aapoker怎么设... 透视讲解!aapoker怎么设置抽水(透视)一起宁德福鼎打炸辅助开挂(都是真的有辅助app)-哔哩哔...
透视指南书!newpoker脚... 透视指南书!newpoker脚本(透视)德州局脚本(辅助)真是是真的有软件(哔哩哔哩)1、起透看视 ...