'Reactjs => axios post method ERROR not working

I wanted to console log the statement but the axios post method seems not to be working it shows no error tho

It logs the user value but doesn't show the "User added"

onSubmit(e) {
    e.preventDefault();
    const user = {
      username: this.state.username,
    }

    console.log(user);

    axios.post('http://localhost:5000/users/add',user)
      .then(res => console.log(res.data));

    this.setState({
      username: ""
    })

user.js

router.route("/add").post((req,res)=>{
  const username = req.body.username;
  const newUser = new User({username});
  newUser.save()
    .then(()=> res.json("User added!"))
    .catch(err=> res.status(400).json("Error "+err))
});

but its not logging "User added"



Solution 1:[1]

Try To Give Username directly instead of passing it as obj may be it work

onSubmit(e) {
    e.preventDefault();
    
      username: this.state.username,
    

    console.log(user);

    axios.post('http://localhost:5000/users/add',username)
      .then(res => console.log(res.data));

    this.setState({
      username: ""
    })

Solution 2:[2]

.save() method doesn't returning anything here, you can return a promise Also change the way of sending json response.

 router.route("/add").post((req,res)=>{
      const username = req.body.username;
      const newUser = new User({username});
       return newUser.save()
        .then(()=> res.json({success: true, message: "User added!"}))
        .catch(err=> res.status(400).json({message:"Error "+err}))
    });

Solution 3:[3]

I didn't know that i have to run both the backend and frontend server simultaneously which in my case is react and nodejs now its working just fine!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohan Kesappagari
Solution 2 Mukesh Maurya
Solution 3 manoj_ontheroll