adnjoo
adnjoo

Reputation: 109

My Axios POST request in a React app is not working

Hi I have an application with GET, POST and DEL requests. One of my POST requests works, but two of my POST requests don't work.

this POST request works

    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: ''
    })
    
}

This POST request doesn't work

    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 = '/';
}

I'm wondering what am I doing wrong? Here's the repository: https://github.com/adnjoo/merncrud

Live application frontend: https://thawing-crag-17351.herokuapp.com/

Live application backend: https://pure-ocean-29656.herokuapp.com/exercises

When I run the server locally and use http://localhost:5000/exercises/add in place of the heroku link, I am able to successfully do the POST request.

I was also able to do the POST request using Postman.

Upvotes: 0

Views: 167

Answers (1)

Muhammad Shahzad Ali
Muhammad Shahzad Ali

Reputation: 149

You just need to remove the redirect line and use in "then"

window.location = '/';

The request is in the process while your page redirect to slash So that's why the request is not proceeding completely

Upvotes: 1

Related Questions