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"
CodePudding user response:
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: ""
})
CodePudding user response:
.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}))
});