在Mac的本地主机上尝试使用Node.js和MongoDB实现登录功能

在Mac的本地主机上尝试使用Node.js和MongoDB进行登录功能的实现。

因为想要创建Web服务,所以将在本地主机上尝试登录功能。我将使用MongoDB和Node.js。省略了Node.js安装的说明。

从MongoDB的安装到启动

安装前的准备工作

brew tap mongodb/brew

安装

brew install mongodb-community

创建储存空间

sudo mkdir /var/lib/mongodb

生成日志

sudo touch /var/log/mongodb.log

启动

sudo mongod --dbpath /var/lib/mongodb --logpath /var/log/mongodb.log

实现登录功能

首先,我们先安装模块。
npm安装express
npm安装monogodb
我认为以下代码可以实现注册和登录。

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const http = require('http').Server(app);

const url = 'mongodb://localhost:27017';
const dbName = 'myMongo';
const connectOption = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
}

const transactionKururiDownload = async (data, res) => {
  let client;
  let login = false;
  try {
    client = await MongoClient.connect(url, connectOption);
    const db = client.db(dbName);
    const collection = db.collection('account');
      await collection.find({}).toArray( (err, docs) => {
        for (const doc of docs) {
          if (doc.mail == data.mail) {
            if (doc.password == data.password) {
              login = true;
              res.sendFile(__dirname + "/index.html");
            }
          }
        }
        if (!login) {
          res.send("login error");
        }
      });
  } catch (error) {
    console.log(error);
  } finally {
//    client.close();
  }
};

const transactionKururiInsert = async (data, res) => {
  let client;
  data = Object.assign(data, {date: new Date() });
  try {
    client = await MongoClient.connect(url, connectOption);
    const db = client.db(dbName);
    const collection = db.collection('account');
    const a = await collection.updateOne({mail:data.mail, password:data.password, name:data.name, date:data.date}, {$set:data}, true );
    if (a.result.n == 0) {
      await collection.insertOne(data);
    }
  } catch (error) {
    console.log(error);
  } finally {
    client.close();
  }
};



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

app.get('/', (req, res) => {
  res.sendFile(__dirname + "/login.html");
});
app.get('/signup', (req, res) => {
  res.sendFile(__dirname + "/signup.html");
});

app.post('/signup', async (req, res) => {
  let client;
  let exist = false;
  try {
    client = await MongoClient.connect(url, connectOption);
    const db = client.db(dbName);
    const collection = db.collection('account');
      await collection.find({}).toArray( (err, docs) => {
        console.log(docs);
        for (const doc of docs) {
          if (doc.mail == req.body.mail){
            console.log(req.body.mail);
            exist = true;
          }
        }

        let user = {mail:"", name:"", password:""};

        if (!exist && req.body.mail != "" && req.body.password != "") {
          user["mail"] = req.body.mail;
          user["password"] = req.body.password;
          user["name"] = user.mail.substr(0, user.mail.indexOf("@"));
          transactionKururiInsert(user, res);

          res.sendFile(__dirname + "/signuped.html");
        } else {
          res.sendFile(__dirname + "/signuperror.html");
        }
      });
  } catch (error) {
    console.log(error);
  } finally {
//    client.close();
  }
});


app.post('/', (req, res) => {

  let user = {
    mail:"", name:"", password:""
  };

  user["mail"] = req.body.mail;
  user["password"] = req.body.password;
  user["name"] = user.mail.substr(0, user.mail.indexOf("@"));
  transactionKururiDownload(user, res);

});

http.listen(8080, () => {
  console.log('listening on :8080');
});

<html>
<head>
    <title>login</title>
</head>
<body style="width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center;">
    <form action="" method="post">
        <h1>login</h1>
        <table>
            <tr>
                <td>mail</td>
                <td><input id="mail" name="mail" type="mail" /></td>
            </tr>
            <tr>
                <td>password</td>
                <td><input id="password" name="password" type="password" /></td>
            </tr>
        </table>
        <button>send</button>
    </form>
    <br>
    <a href="signup">sign up</a>
</body>
</html>

<html>
<head>
    <title>signup</title>
</head>
<body style="width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center;">
    <form action="" method="post">
        <h1>signup</h1>
        <table>
            <tr>
                <td>mail</td>
                <td><input id="mail" name="mail" type="mail" /></td>
            </tr>
            <tr>
                <td>password</td>
                <td><input id="password" name="password" type="password" /></td>
            </tr>
        </table>
        <button>send</button>
    </form>
</body>
</html>
<!Doctype html>
<html>
  <head>
    <title>logined</title>
  </head>
  <body style="width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center;">
    <h1>Success signup!</h1>
    <a href="/">please login</a>
  </body>
</html>
<!Doctype html>
<html>
  <head>
    <title>error</title>
  </head>
  <body style="width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center;">
    <h1>signup error</h1>
  </body>
</html>
<!DOCTYPE html>
<html>
    <head>
        <title>test</title>
    </head>
    <body>
        login success!
    </body>
</html>