node初始化項目一點通(操作數據庫,創建路由)

1.首先我們使用webstrom創建node環境,如下圖


image.png

2.接下來我們安裝
body-parser模塊(用於post請求)
mongoose模塊(用於連接數據庫)

npm install body-parser mongoose --save-dev

image.png

在app.js中引入body-parser模塊

3.在最外層創建model文件夾用來創建model層(操作數據庫的都是model的實例)

image.png

4.下面是model

const mongoose=require("mongoose");
const DB_URL='mongodb://localhost:27017/user';

//鏈接數據庫
mongoose.connect(DB_URL);


const models={
    user:{
        "username":{type:String,require:true},
        "password":{type:String,require:true}
    }
}

//根據models創建model
for(let m in models){
    mongoose.model(m,new mongoose.Schema(models[m]))
}

//獲取model的方法
module.exports={
    getModel:function (name) {
        return mongoose.model(name);
    }
}

5.前綴爲user的路由

const express = require('express');
const router = express.Router();
const path=require('path');

//因爲我們要對數據庫操作,所以我們要引入model
const model=require("../models/model");
const User=model.getModel("user");

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

//轉到register模板
router.get("/register",function (req,res,next) {
    res.render("register");
});

router.post("/register",function (req,res,next) {
    const {username,password}=req.body;

    //查詢,
    User.find({username},function (err,doc) {
        if(err){
          return res.json({code:1,msg:"用戶名重複"});
        }
        //保存之前先要新建model
        const userModel=new User({username,password});
        userModel.save(function (e,d) {
            if (e) {
                return res.json({code:1,msg:'後端出錯了'})
            }
            const {username, password, _id} = d;
            return res.json({code:0,data:{username, password, _id}})
        });
    })

});

module.exports = router;

6.index.ejs

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
    <a href="/users/register">註冊</a>
  </body>
</html>

7.register.ejs

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
  <p><span>用戶名:</span><input type="text" id="username"></p>
  <p><span>密碼:</span><input type="password" id="password"></p>
  <button id="btn">提交</button>
  </body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  <script>
      (function () {
          $("#btn").click(function () {
              var username=$("#username").val();
              var password=$("#password").val();
              
              $.ajax({
                  type:"POST",
                  url:"/users/register",
                  data:{username:username,password:password},
                  success:function (result) {
                      
                  },
                  error:function () {
                      
                  }
              });
              
          });
      })();

  </script>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章