Faisal Malik
Faisal Malik

Reputation: 77

How to handle data being sent by Axios post request?

I have a react frontend and node.js backend.

I am successfully sending the POST request using axios:

  const [logins, setLogins] = useState({});


  function updateLogins(e) {
    setLogins({...logins, [e.target.name]:e.target.value})
  }

  function submitHandler() {
    console.log(logins)
    axios({
      method: 'post',
      url: 'http://localhost:3001/api/login',
      data: logins
    })
    .then( (res) => {
      console.log(res)
    })
  }

I am seeing the login information from my input fields being received as an object in the console, I am wondering what steps does one take to capture this data in the backend and then save it to mongoDB atlas. (Using Mongoose)

Upvotes: 0

Views: 1331

Answers (1)

J. Cutshall
J. Cutshall

Reputation: 352

So if you are getting your post request on the back end you will want to first do some error checking on the login field like whether every input field needed is filled etc.

make sure you are connected to your atlas cluster. how to connect mongoose

On your backend with mongoose you have to have a Schema to define the "shape" of the data you are inputing & a Model created from you schema for each document.

Here is a bit of code from a app i created using node.js, Express.js, mongoose for users to register.

users.post('/register', async (req, res) => {
    try {
        let { email, password, passwordCheck, username } = req.body
        // ERROR CHECKING
        if( !email || !password || !passwordCheck) {
            return res.status(400).json({msg: "Not all fields have been entered."})
        }
        if(password.length < 5){
            return res.status(400).json({msg: "The password needs to be atleast 5 characters long."})
        }
        if (password !== passwordCheck) {
            return res.status(400).json({msg: "Passwords do not match!"})
        }
        const existingUser = await User.findOne({email: email })
        if (existingUser) {
            return res.status(401).json({msg: "An account with this email already exists"})
        }
        if (!username) {
            username = email
        }

        // Password HASHING
        const salt = await bcrypt.genSalt()
        const passwordHash = await bcrypt.hash(password, salt)
        
        // this is where we create out new User using the User model
        const newUser = new User({
            email,
            password: passwordHash,
            username
        })
        // this is where we tell mongoose to save the newly created document to mongoDB
        const savedUser = await newUser.save()
        res.status(200).json(savedUser)

    } catch (err) {
        res.status(500).json({error: err.message})
    }

})

If you need some help with connecting, or creating a schema/model let me know.

Upvotes: 1

Related Questions