使用Axios,React.js和Spring进行简单的发布请求

时间:2020-02-22 16:34:53

标签: reactjs spring rest axios

我是React和Spring的新手,创建一个简单的JSON Post请求时遇到了麻烦。在控制台中成功记录了发布请求,但未添加任何数据。以下是相关的脚本:

package com.sdproject.teammanager.model;

public class Team {
    private String id;
    private String name;
    private int seeding;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSeeding() {
        return seeding;
    }

    public void setSeeding(int seeding) {
        this.seeding = seeding;
    }

}
package com.sdproject.teammanager.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.sdproject.teammanager.exception.TeamNotFoundException;
import com.sdproject.teammanager.model.Team;
@CrossOrigin(origins ="http://localhost:3000")
@RestController
public class TeamController {
    private static Map<String, Team> teamRepo = new HashMap();
    static {
        Team nuig = new Team();
        nuig.setId("1");
        nuig.setName("NUIG");
        nuig.setSeeding(1);

        teamRepo.put(nuig.getId(), nuig);
    }

    @RequestMapping(value = "/teams")
    public ResponseEntity<Object> getTeam() {
        return new ResponseEntity<>(teamRepo.values(), HttpStatus.OK);
    }

    @RequestMapping(value = "/teams", method = RequestMethod.POST)
    public ResponseEntity<Object> createTeam(@RequestBody Team team) {
        teamRepo.put(team.getId(), team);
        return new ResponseEntity<>("Team has been registered", HttpStatus.CREATED);
    }

    @RequestMapping(value = "/teams/{id}", method = RequestMethod.PUT)
    public ResponseEntity<Object> updateTeam(@PathVariable("id") String id, @RequestBody Team team) {
        if (!teamRepo.containsKey(id))
            throw new TeamNotFoundException();
        teamRepo.remove(id);
        team.setId(id);
        teamRepo.put(id, team);
        return new ResponseEntity<>("Team Has Been Updated Successfully", HttpStatus.OK);
    }

    @RequestMapping(value = "/teams/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Object> delete(@PathVariable("id") String id) {
        if (!teamRepo.containsKey(id))
            throw new TeamNotFoundException();
        teamRepo.remove(id);
        return new ResponseEntity<>("Team Has Been Deleted", HttpStatus.OK);
    }
}
import React from 'react';
import axios from 'axios';

export default class TeamInput extends React.Component {
    state = {
        name: '',
    }

    handleChange = event => {
        this.setState({ name: event.target.value });
    }

    handleSubmit = event => {
        event.preventDefault();

        const Team = {
            name: this.state.name
        };

        axios.post(`http://localhost:8080/teams`, { team })
            .then(res => {
                console.log(res);
                console.log(res.data);
            })
    }

    render() {
        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                    <label>
                        Team Name:
                        <input type="text" name="name" onChange={this.handleChange} />
                    </label>
                    <button type="submit">Add</button>
                </form>
            </div>
        )
    }
}

点击我的按钮提交具有默认参数的团队后,我可以看到它已成功提交。但是它没有显示在仓库中,或者当我使用邮递员获取JSON文件时。

2 个答案:

答案 0 :(得分:0)

类似于Java类,Team没有定义getter方法。 您应该为getter使用spring注释,或者应该已经定义了getter。 这可能是问题的根本原因。 如果没有,您能否在这个问题上更清楚?

答案 1 :(得分:0)

我希望它能为您服务

async handleChange = event => {
        await this.setState({ [event.target.name]: event.target.value });
    } 


  handleSubmit = e => {
        e.preventDefault();
        const data = {
                name: this.state.name
          };
        axios({
          method: "post",
          url: `http://localhost:8080/teams`,
          data
        })
          .then(res => {
            this.setState({
               name: '',
            }); 
          })
          .catch(err => {
            console.log(err);
          });
      }
相关问题