简体   繁体   English

如何通过 REST API 处理 MongoDB 登录?

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

I'm not sure how to check if the values match with the MongoDB data.我不确定如何检查值是否与 MongoDB 数据匹配。 I am using PUT and trying to use findOneAndUpdate to check if the values match.我正在使用PUT并尝试使用findOneAndUpdate来检查值是否匹配。

<script>
const logindetails = new Vue({
el: '#logindetails',
data: {

    email: "",
    password: "",
    on: Boolean
},

methods: {
    login: function (e) {
        e.preventDefault();

        const log = {
            email: this.email,
            password: this.password,
        }

        const options = {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(log)
        };

       fetch('http://localhost:3000/users/${this.email}/${this.password}', 
options).then(response => {

[...]

</script>

This is the server code (it successfully connected to MongoDB) :这是服务器代码(它成功连接到 MongoDB):

app.put('/students/:email/:password', (req, res, next) => {
console.log("login");
res.setHeader("Content-Type", "application/json");
db.collection('users').findOne({email: (req.params.email), password: (req.params.password)},
    {$set: {on: true}})
    .then(results => res.send(results))
    .catch(err => res.send(err))
});

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.我个人认为将您的用户名和密码作为查询字符串不是一个好主意,因为它损害了 restful api 约定。 It wouldn't make sense to use a put request if there is no body being pass.如果没有传递主体,则使用 put 请求是没有意义的。 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 1.(客户端)在获取请求的正文中发送电子邮件和密码

//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 ) 2. (服务器端 -确保您使用 app.use(express.json()) 访问 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}`);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM