【问题标题】:My Axios POST request in a React app is not working我在 React 应用程序中的 Axios POST 请求不起作用
【发布时间】:2021-04-20 21:59:32
【问题描述】:

您好,我有一个带有 GET、POST 和 DEL 请求的应用程序。我的一个 POST 请求有效,但我的两个 POST 请求无效。

这个 POST 请求有效

    onSubmit(e) {
    e.preventDefault();

    const user  = {
        username: this.state.username
    }

    console.log(user);

    axios.post('https://pure-ocean-29656.herokuapp.com/users/add', user)
        .then (res=> console.log(res.data));
        

    this.setState ({
        username: ''
    })
    
}

这个 POST 请求不起作用

    onSubmit(e) {
    e.preventDefault();

    const exercise  = {
        username: this.state.username,
        description: this.state.description,
        duration: this.state.duration,
        date: this.state.date
    }

    console.log(exercise);

    axios.post('https://pure-ocean-29656.herokuapp.com/exercises/add', exercise)
        .then(res => console.log(res.data));


    window.location = '/';
}

我想知道我做错了什么?这是存储库:https://github.com/adnjoo/merncrud

实时应用前端:https://thawing-crag-17351.herokuapp.com/

实时应用后端:https://pure-ocean-29656.herokuapp.com/exercises

当我在本地运行服务器并使用 http://localhost:5000/exercises/add 代替 heroku 链接时,我能够成功执行 POST 请求。

我还能够使用 Postman 发出 POST 请求。

【问题讨论】:

  • 你可能会立即做某事,而不是把你想要在请求之后发生的事情放在 axios 回调中。把你想要在请求之后发生的事情放在 axios 回调中。
  • “不工作”非常不具体。你有错误吗?哪些?

标签: reactjs express axios


【解决方案1】:

您只需要删除重定向行 并在“then”中使用

window.location = '/';

请求正在处理中,而您的页面重定向到斜线所以这就是请求没有完全进行的原因

【讨论】:

    猜你喜欢
    • 2020-11-09
    • 2018-12-25
    • 2018-08-23
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2020-09-20
    • 2019-09-18
    相关资源
    最近更新 更多