node筆記1:vue+node+mongodb+studio 3T建立登入模組

salad633發表於2024-04-12

1.建立node專案:

express node
npm i
package.json修改如下程式碼,便於每次修改程式碼都可以重新整理頁面:
"scripts": { "start": "node-dev ./bin/www" }

2.如果配合node設定反向代理;

3.新增mongoose模組提供資料庫資訊:npm i mongoose --save

4.以登入功能模組為例,專案檔案如下:

models資料夾=>UserModel.js:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const UserType = {
    username: String,
    password: String,
    gender: Number,
    introduction: String,
    avatar: String,
    role: Number, 
}

const UserModel = mongoose.model('user', new Schema(UserType))
module.exports = UserModel

services資料夾=>UserService.js:

const UserModel = require("../../models/UserModel")

const UserService = {
    login: async({username,password})=> {
        return UserModel.find({
            username,
            password
        })
    }
}

module.exports = UserService

controllers資料夾=>UserController.js:

const UserService = require("../../services/admin/UserService")

const UserController= {
    login: async(req,res)=>{
        console.log(req.body)
         var result = await UserService.login(req.body)
         console.log(result.length)
         if(result.length === 0){
            res.send({
                code: '-1',
                error: '使用者名稱密碼不匹配'
            })
         }else{
            res.send({
                ActionType: 'OK'
            })
         }
    }
}

module.exports = UserController

routes檔案=>UserRouter.js:

var express = require('express');
const UserController = require('../../controllers/admin/UserController');
var UserRouter = express.Router();

UserRouter.post("/adminapi/user/login",UserController.login)
module.exports = UserRouter;

app.js:

const UserRouter = require('./routes/UserRouter');
app.use(UserRouter)

5.連線資料庫Studio 3T

config資料夾=>db.config.js:

const mongoose = require('mongoose')
mongoose.connect("mongodb://localhost:27017/my-database")

bin資料夾=>www:

require("../config/db.config")

大功告成,檢視你的Studio 3T吧,資料庫mongodb安裝檢視上一篇!

相關文章