首页 > 解决方案 > Spring Boot:从表单(reactjs)提交中获取空输入

问题描述

我有一个基本的表单提交 Spring Boot 应用程序。我的问题是当我提交表单时,我得到空结果。

这是我的表单代码:

package io.group.artifact.MainApplication.TopicController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
@CrossOrigin(origins = "http://localhost:3000")
@RestController
public class TopicControl {
    @Autowired
    private TopicService topicService;

    @RequestMapping("/topics")
    public List<Topic> getTopic(){

        return topicService.getAllTopics();


    }
    @RequestMapping("/topics/{id}")
    public Topic getTopic(@PathVariable String id) {
    return topicService.getTopic(id);
    }
    @RequestMapping(method= RequestMethod.POST, value = "/topics")
    public void addTopic(@RequestBody Topic topic){
        topicService.addTopic(topic);
    }

    @RequestMapping(method= RequestMethod.PUT, value = "/topics/{id}")
    public void updateTopic(@RequestBody Topic topic, @PathVariable String id){
        topicService.updateTopic(id, topic);
    }

    @RequestMapping(method= RequestMethod.DELETE, value = "/topics/{id}")
    public void deleteTopic(@PathVariable String id){
        topicService.deleteTopic(id);
    }
}

这段代码是我的反应部分:

    saveEmployee = (e) => {
        e.preventDefault();
        let employee = {firstName: this.state.firstName, iD: this.state.iD, desc: this.state.desc};
        console.log('employee => ' + JSON.stringify(employee));

        EmployeeService.createEmployee(employee).then(res =>{
            this.props.history.push('/topics');
        
        });

    }

这也是前端代码

import axios from 'axios';

const EMPLOYEE_API_BASE_URL = "http://localhost:8080/topics";

class EmployeeService {

    getEmployees(){
        return axios.get(EMPLOYEE_API_BASE_URL);
    }

    createEmployee(employee){
        return axios.post(EMPLOYEE_API_BASE_URL, employee);
    }

}

export default new EmployeeService()

在 http://localhost:8080/topics 我得到以下输出:

在此处输入图像描述

标签: reactjsspring-bootspring-mvc

解决方案


通过查看此代码,来自前端的参数和请求正文 DTO 中的字段是不同的,这是错误的,因为两者都应该匹配,然后才会起作用。

前端 :

名字,ID,描述

后端:

名称、ID、描述

确保这些在双方都是相同的。


推荐阅读