【问题标题】:Why is my axios post request not working and sending null strings?为什么我的 axios 发布请求不起作用并发送空字符串?
【发布时间】:2021-10-05 05:00:00
【问题描述】:

在一个简单的应用程序上制作了一个简单的聊天组件来学习全栈,但我不确定为什么当我在 react 上使用 axios 时我的帖子请求不起作用,即使当我在邮递员上发送帖子请求时它也有效。所以,我认为问题出在我的代码中。在邮递员中,当我在键中输入用户名和消息并为它们提供字符串值时,它可以工作(请参阅底部的最终 console.log)。但是当我使用我的代码这样做时,它发送的是空值而不是我传递的字符串值。即使我使用 JSON.stringify ,axios 最终还是发送了 [object] ,这是问题吗?如果没有,我做错了什么?非常感谢。这是我的代码:

updateChat = e => {
        e.preventDefault();
        const { chat , username , chats } = this.state;

        this.setState({ chat : e.target.value });

        chats.push(chat);

        console.log("username: " + username + ", message: " + chat)

        var body = { 
            username : username,
            message : chat };

        console.log("body: " + body)

        axios({
            method: 'post',
            url : 'http://localhost:8080/api/chats/add', 
            data: body
        })
        .then(function (response) {
            console.log("Submitted: " + response);
        })
        .catch(function (error) {
            console.log("Post error: " + error);
        });
        this.pullChats();
    }

pullChats() {
        axios.get('http://localhost:8080/api/chats')
        .then(res => {
            this.setState({ chats : res.data });
            console.log(res.data); 
        })
        .catch(function (error) {
            console.log("Error: " + error);
        });
    }

<div>
                {chats.map(chats =>
                <span className="badge badge-pill badge-warning p-3">
                    <p>{chats.message}</p> Username: <span className="text-green">{chats.username}</span>
                </span>)}
                <p>Posting as(username): <span className="text-green">{username}</span></p>
                <input type="text" value={chat} onChange={this.handleChatAddition}/>
                <button className="btn btn-light" onClick={this.updateChat}>Send</button>
            </div>

当我使用 Console.log 时:

username: USERNAME, message: testest

第二行:

body: {"username":"USERNAME","message":"testest"}

第三行:

Submitted: [object Object]

第 4 行:(id 为 1、2、6、7 和 8 的对象是从邮递员创建的,而其余对象是使用 axios 创建的。出于某种原因,当我使用 axios 时,我会推入空值,即使它们是字符串,我不知道为什么)

(15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {id: 1, username: "UsernameABC", message: "This is my question"}
1: {id: 2, username: "User2", message: "Okokok"}
2: {id: 3, username: null, message: null}
3: {id: 4, username: null, message: null}
4: {id: 5, username: null, message: null}
5: {id: 6, username: "testesttesttrtr", message: "hitest"}
6: {id: 7, username: "testesttesttrtr", message: "hitest"}
7: {id: 8, username: "testesttesttrtr", message: "hitest"}
8: {id: 9, username: null, message: null}
9: {id: 10, username: null, message: null}
10: {id: 11, username: null, message: null}
11: {id: 12, username: null, message: null}
12: {id: 13, username: null, message: null}
13: {id: 14, username: null, message: null}
14: {id: 15, username: null, message: null}
length: 15
__proto__: Array(0)

顺便说一句,这是我的后端:

控制器:

@CrossOrigin(origins="*")
@RestController
@RequestMapping("api/")
public class ChatController {
    
    @Autowired
    private ChatRepository chatRepository;
    
    @GetMapping("chats")
    public List<Chat> getChats(){
        return this.chatRepository.findAll();
    }
    
    @PostMapping("chats/add")
    public Chat addChat( Chat newChat) {
        return chatRepository.save(newChat);
    }

}

型号:

@Entity
@Table(name="users")
public class Chat {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    
    @Column(name = "username")
    private String username;
    
    @Column(name = "message")
    private String message;
    public long getId() {
        return id;
    }
    
    public Chat() {
        
    }
    
    public Chat(String username, String message) {
        super();
        this.username = username;
        this.message = message;
    }



    public void setId(long id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

存储库:

@Repository
public interface ChatRepository extends JpaRepository<Chat, Long> {

} 

应用:

@

SpringBootApplication
public class ChatBackendApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(ChatBackendApplication.class, args);
    }

    
    @Autowired
    private ChatRepository chatRepository;
    
    @Override
    public void run(String... args) throws Exception {
        this.chatRepository.save(new Chat("UsernameABC", "This is my question"));
        this.chatRepository.save(new Chat("User2", "Okokok"));
        
    }

}

【问题讨论】:

    标签: java post axios


    【解决方案1】:

    您是否尝试过以下方法使用 axios 进行 post 请求?

    axios.post('http://localhost:8080/api/chats/add', { username: username, message: chat })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    

    类似于您的获取请求

    【讨论】:

    • 是的,由于某种原因,我也尝试过同样的结果:/
    • 不要使用动态变量,而是尝试使用简单的字符串,例如。用户名:“name1”和消息:“message1”。看看它是否响应了预期的结果
    • 是的,即使我直接发送字符串,它也会返回相同的结果,它们仍然被记录为null
    猜你喜欢
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-21
    • 2018-03-22
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多