简体   繁体   English

ReactJS:使用按钮执行 POST 和 GET 请求

[英]ReactJS: Perform a POST & GET request with a button

I am trying to do something like a post and get request with one click.我正在尝试做一些类似帖子的事情,并通过单击获得请求。 I need to do something like that, because practically speaking, I am trying to implement a "create game lobby" button, that when clicked creates a game on the backend which is written in java and also to get the creator directly routed to this newly created game.我需要做类似的事情,因为实际上,我正在尝试实现一个“创建游戏大厅”按钮,单击该按钮时会在后端创建一个游戏,该游戏写在 java 中,同时让创建者直接路由到这个新的创建的游戏。 Does anyone know a way how to tackle this?有谁知道如何解决这个问题?

Greetings问候

Your question is very broad but I'd put an example on how it could look:您的问题非常广泛,但我会举一个例子说明它的外观:

This is how you can create your button:这是创建按钮的方法:

<button onClick={this.handleClick}/>

This is how you can do a post request when the button is pressed:这是按下按钮时如何执行发布请求:

handleClick (event) {
    axios.post('/myUrl')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
 }

It wouldn't make sense to send both post and get requests for the task you are trying to accomplish here.对于您要在此处完成的任务,同时发送帖子和获取请求是没有意义的。 You will have to wait for the game to be created first, and then reroute the user to the game.您必须先等待游戏创建完毕,然后再将用户重新路由到游戏。 The general way of doing this is to return the game id/link as the response to the post request, and then redirect the user to that link.这样做的一般方法是返回游戏 ID/链接作为对发布请求的响应,然后将用户重定向到该链接。

    async function handleCreateNewGame() {
        const data = this.state.data;
        const res = await axios.post('api/game/create', {...data});
        if(res.status === 200) {
            const game_id = res.data.id;
            window.location.replace(`/game/${game_id}`); //You might want to use something like history.push() instead
        } else {
            alert('Create ERR');
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM