首页 > 解决方案 > 如何通过 REST API 处理 MongoDB 登录?

问题描述

我不确定如何检查这些值是否与 MongoDB 数据匹配。我正在使用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>

这是服务器代码(它成功连接到 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))
});

标签: node.jsmongodbrestexpressvue.js

解决方案


我个人认为将您的用户名和密码作为查询字符串不是一个好主意,因为它会损害 restful api 约定。如果没有正文通过,则使用 put 请求是没有意义的。此外,在登录情况下发布请求会更有意义。无论如何我离题了,这里是进行身份验证的常用步骤。

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. (服务器端 -确保您使用 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}`);
})

推荐阅读