[Vuejs]-How to handle login with MongoDB through REST API?

0👍

I personally don’t think it is a good idea to put your username and password as query string, because it hurts the restful api convention. It wouldn’t make sense to use a put request if there is no body being pass. Also, a post request would make more sense in a login situation .Anyway I digress, here are the usual steps to doing authentication.

1. (Client-Side) Send the email and password in the body of the fetch request

//something like this

const body = { email, password };
  const response = await fetch(
    "http://localhost:5000/authentication/login",
    {
      method: "POST",
      headers: {
        "Content-type": "application/json"
      },
      body: JSON.stringify(body)
    }
  );

2.(Server-Side – make sure you to use app.use(express.json()) to access req.body)

//defining middleware to access req.body

app.use(express.json());

app.post("/authentication/login", async(req,res) =>{
    //1. destructure email and password

    const {email, password} = req.body

    //2. check if user doesn't exist

    const user = await db.user.find({user_email: email})
    if(!user){
        return res.status(401).send("User does not exist");
    }

    //3. Check if password is the same as the password in the database

    if(password !== user.password){
        return res.status(401).send("Wrong Credential")
    }

    //4. This is up to you when the user is authenticated

    res.json(`Welcome back ${email}`);
})

Leave a comment