Home > Mobile >  Then and Catch not running on successful Axios Post request on Backend
Then and Catch not running on successful Axios Post request on Backend

Time:06-09

I'm making a simple react app which I can input a name, last name and googleId in 3 input fields. I used onchange and react hooks to send the data in the input fields to my express backend when the user clicks the submit button in the react code. Whenever I press the button it console logs the body and the things I wrote in the input field appear correctly... I'm so confused. I have to refresh to see the stuff I wrote in a new input field, and it's supposed to make a new input field appear without having to fresh because of what I put in the .then, but that isn't running so it won't work.

React Code

import React from "react";
import Axios from "axios";


function App(){
    const [listOfUsers, setListOfUsers] = React.useState([])
    const [name, setName] = React.useState("");
    const [lastName, setLastName] = React.useState("");
    const [googleId, setGoogleId] = React.useState("");

    React.useEffect(()=>{
        Axios.get("http://localhost:3001/getUsers").then((response)=>{
            console.log(response);
            setListOfUsers(response.data);
        });
    }, []);

 
    /*function createUser(){
        fetch("http://localhost:3001/createUser", {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body: new URLSearchParams({
                name: name,
                lastName: lastName,
                googleId: googleId
            })  
        }).then(res=>{
            console.log("WHY");
            console.log(res);
        });
    }*/

    console.log("what");
    function createUser(){
        console.log("what"); /* This prints */
        console.log(name); /*This prints the variable name correctly */
        const response = Axios.post("http://localhost:3001/createUser", 
            new URLSearchParams({          
                name: name, 
                lastName: lastName, 
                googleId:googleId
            }), {headers:{"Content-Type":"application/x-www-form-urlencoded"}}
        )
        .then((response)=>{
            console.log("whast");
            console.log("why is this not printing");
            setListOfUsers(...listOfUsers, {name:name, lastName:lastName, googleId:googleId})
            console.log(response);
        }) /* Nothing in the then response */
        .catch((error)=>{
            console.log(error.resonse); /*Nothing here either */
        });
        console.log("hey im done") /* This prints */
    } 


    return (
        <div className="usersDisplay">
            {
                listOfUsers.map((user)=>{
                    return (<h1 key={Math.random()}>Name:{user.name}</h1>)
                })
            }

            <div>
                <input type="text" name="name" onChange={(event)=>{setName(event.target.value)}} placeholder="Name..." value={name}/>
                <input type="text" name="lName" onChange={(event)=>{setLastName(event.target.value)}} placeholder="LastName..." value={lastName}/>
                <input type="text" name="id" onChange={(event)=>{setGoogleId(event.target.value)}} placeholder="GoogleId..." value={googleId}/>
                <button onClick={createUser}>Create User</button>
            </div>
        </div>
    )
};


export { App };

Express Backend

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const cors = require("cors");

const app = express();

app.use(bodyParser.urlencoded({extended:true}));
app.use(cors());

/*mongoose.connect("mongodb srv://{hiddenlogin}[email protected]/?testretryWrites=true&w=majority")*/
mongoose.connect("mongodb srv://{hiddenlogin}@cluster0.87hm5lv.mongodb.net/?retryWrites=true&w=majority")

const userSchema = new mongoose.Schema({
    name: String,
    lastName: String,
    googleId: String,
    blogs: [],
    likedPosts: []
});
  
const blogSchema = new mongoose.Schema({
    name: String,
    googleId: String,
    likes: Number,
    authorFirst: String,
    authorLast: String,
    content: String,
    cutDownContent: String
})

    
const Blog = new mongoose.model("Blog", blogSchema);

const User = new mongoose.model("User", userSchema);

app.get("/getUsers", (req, res)=>{
    User.find({}, (err, results)=>{
        if (err){res.json(err)};
        res.json(results);
    });
});

app.post("/createUser", async (req, res)=>{
    console.log(req.body);
    const newUser = new User({
        name: req.body.name,
        lastName: req.body.lastName,
        googleId: req.body.googleId,
        blogs: [],
        likedPosts: []
    });
    await newUser.save();
    res.json({"sucess":true});
    console.log("Wow!");
});

app.listen(3001, ()=>{
    console.log("Listening on port 3001");
});

I've been searching for hours figuring out why the .then and .catch won't run and tried several solutions, even tried doing fetch but that didn't even work.

CodePudding user response:

Try this one:

axios.post('http://localhost:3001/createUser', {
  name: name, 
  lastName: lastName, 
  googleId:googleId
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

And do check the chrome dev tools network tab for debugging.

CodePudding user response:

So apparently I just had to restart everything, as when I started everything back up it started to work. Sorry everyone.

  • Related