我在 React 应用程序中的 Axios POST 请求不起作用

时间:2021-04-20 21:59:32

标签: reactjs express axios

嗨,我有一个带有 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 请求。

1 个答案:

答案 0 :(得分:1)

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

window.location = '/';

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

相关问题