【问题标题】:Making Simple Post Request With Axios, React.js and Spring使用 Axios、React.js 和 Spring 进行简单的发布请求
【发布时间】:2020-06-06 19:21:22
【问题描述】:

我是 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>
        )
    }
}

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

【问题讨论】:

    标签: reactjs spring rest axios


    【解决方案1】:

    看起来像您的 Java 类,Team 没有定义 getter 方法。 要么你应该为 getter 使用 spring 注释,要么应该定义一个 getter。 这可能是您的问题的根本原因。 如果不是,您能否更清楚地说明这个问题?

    【讨论】:

    • 嗨,我已经用我的完整 Team 类和完整的控制器类更新了我的初始问题。希望这可以澄清一些事情。
    • 当我模仿您的代码并在邮递员中尝试您的发布请求以创建团队时。它确实回复了添加的团队名称。仅见 [ { "id": null, "name": "somename", "seeding": 0 }, { "id": "1", "name": "NUIG", "seeding": 1 } ],问题是 id 为空。
    • 另外,const Team = { name: this.state.name }; axios.post(http://localhost:8080/teams, { Team }) 对象名称应该相同。 T 应该是大写的。
    • 从团队更改为团队允许我发布请求并在 repo 中查看新的 JSON 对象!但是我认为我的事件处理存在错误,因为名称显示为 null 即使我可以看到在发布请求中传递了输入的字段。
    • 我发现了您的问题 :) 仅对团队使用小写字母。在变量 team 的声明和 axios.post 请求中。另外,不要将团队封装在 {} 中,仅将对象作为 team 发送,如下所示:const Team = { name: this.state.name }; axios.post(http://localhost:8080/teams, team )
    【解决方案2】:

    希望对你有用

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

    【讨论】:

      猜你喜欢
      • 2021-04-28
      • 2021-12-25
      • 2021-09-01
      • 2022-12-10
      • 2017-10-02
      • 2018-09-11
      • 2018-10-17
      • 2018-06-27
      • 2022-09-25
      相关资源
      最近更新 更多