在Angular中提交的表单数据在Spring Boot中显示为空的问题可能有多个原因。以下是一些可能的解决方法:
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);
});
}
}
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方法
}
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);
});
}
}
以上是一些可能的解决方法,但具体解决方法可能因具体情况而异。您可以根据您的代码和需求进行调整和修改。