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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Axios,React.js和Spring进行简单的发布请求相关的知识,希望对你有一定的参考价值。

我对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文件时。

答案

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

另一答案

我希望它能为您工作

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

以上是关于使用Axios,React.js和Spring进行简单的发布请求的主要内容,如果未能解决你的问题,请参考以下文章

react.js 使用 axios 发布数据到 php,但是 php echo 为空

使用 Axios 将对象从 React.js 发布到 PHP

React js 和 axios POST 请求发送空数组

Axios 没有使用 useEffect() (React Js) [重复]

Axios 发布请求在 React JS 中不起作用

React.js - 如何使用 axios POST 方法将数据从 div 传递到函数?