美文网首页
MongoDB+node.js+experss+vue.js构建

MongoDB+node.js+experss+vue.js构建

作者: zx一个胖子 | 来源:发表于2018-08-24 17:26 被阅读0次

文中有很多注释,新手可以仔细看看。
文章最后有项目的github地址

准备工作: 全局安装好 vue脚手架,npm install --global vue-cli 我这里用的是脚手架2.0版本。
安装配置mongodb: https://www.jianshu.com/p/ff0edacd3430

在E盘 打开命令框,vue init webpack nodeapp 创建你的项目(项目名不能有大写)
安装 express 与mongoose
cnpm express install --save
cnpm mongoose install --save (这个有时候会下载报错,可以直接写进package.json "mongoose": "^5.0.3")


QQ图片20180824113510.png

然后 cnpm install 下载各个模块。
完成准备工作后开始我们的项目。

一. node.js 与数据库的连接与接口的编写。
打开nodeapp文件,在根目录中创建server文件夹,在server中创建api.js db.js index.js 三个js文件


QQ图片20180907102426.png

1.在db.js中 编写与数据库连接的代码

//mongoose通过三个模块去创建一个数据库集合,还有定义"集合"的基本组成结构并使其具有相应的操作数据库能力。
//Schema  Model  Entity
const mongoose = require('mongoose');
//这里是连接到我的数据库,默认是mongodb://127.0.0.1:27017/text
mongoose.connect("mongodb://127.0.0.1:27017/zhao");
//绑定事件
const db = mongoose.connection;
//mongoose.connection的两个方法,error与open 代表连接失败和连接成功
db.on('error',(error) => console.log('Mongo connection error'+error));
db.once('open',() => console.log('Mongo connection successed'));

//1.Schema  数据库集合的模型骨架,或者是数据属性模型传统意义的表结构。
const loginSchema = mongoose.Schema({
  name : String,
  password : String
});
//2.Model 通过Schema构造而成,除了具有Schema定义的数据库骨架以外,还可以具体的操作数据库。
//这里表示在zhao数据库中创建了一个users的表,并且格式为loginSchema中所定义的
const Models = {
    Login : mongoose.model('users',loginSchema)
}

module.exports = Models;

可以启动数据库,然后在server下输入命令:node db.js 查看是否连接成功。


QQ图片20180824160514.png

连接成功!!

  1. api.js 编写接口
const models = require('./db');
const express = require('express');
const router = express.Router();//这里用到了express的路由级中间件

//注册账号的接口
//  /api为代理的服务
router.post('/api/user/register',(req,res) => {
    //这里的req.body 其实使用了body-parser中间件 用来对前端发送来的数据进行解析
    //查询数据库中name= req.body.name 的数据
    models.Login.find({name: req.body.name},(err,data) => {
        if(err){
            res.send({'status': 1002, 'message': '查询失败', 'data': err});
        }else{
            console.log('查询成功'+data)
            //data为返回的数据库中的有相同name的集合
            if(data.length > 0){
                res.send({'status': 1001, 'message': '该用户名已经注册!'});
            }else{
                let newName = new models.Login({
                    name : req.body.name,
                    password : req.body.password
                });
                //newName.save 往数据库中插入数据
                newName.save((err,data) => {
                    if (err) {
                        res.send({'status': 1002, 'message': '注册失败!', 'data': err});
                    } else {
                        res.send({'status': 1000, 'message': '注册成功!'});
                    }
                });
            }
        }
    })
})
//登录接口
router.post('/api/user/login',(req,res) => {
    models.Login.find({name: req.body.name, password: req.body.password},(err,data) => {
        if (err) {
            // res.send(err);
            res.send({'status': 1002, 'message': '查询数据库失败!', 'data': err});
        } else {
            console.log(data)
            if (data.length > 0) {
                res.send({'status': 1000, 'message': '登录成功!', 'data': data});
            } else {
                res.send({'status': 1001, 'message': '登录失败,该用户没有注册!', 'data': err});
            }
        }
    })
})
//获取所有账号的接口
router.get('/api/user/all',(req,res) => {
    // 通过模型去查找数据库
    models.Login.find((err,data) => {
        if (err) {
            res.send(err);
        } else {
            res.send(data);
        }
    });
});
//删除账号接口
router.post('/api/user/delete',(req,res) => {
    // 通过模型去查找数据库
    models.Login.remove({name: req.body.name},(err,data) => {
        // if (err) {
        //     res.send(err);
        // } else {
        //   res.send({'status': 1003, 'message': '删除成功!', 'data': data});
        // }
    });
    models.Login.find((err,data) => {
        if (err) {
            console.log(err)
        } else {
            res.send({'status': 1000, 'message': '更新成功!', 'data': data});
        }
    });
});

module.exports = router;
  1. index.js express综合处理模块
const api = require('./api');
//操作文件,读写文件
const fs = require('fs');
const path = require('path');
//解析前端发送来的数据
const bodyParser = require('body-parser')
const express = require('express');
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(api);
// express.static 用来处理静态资源
app.use(express.static(path.resolve(__dirname, '../dist')));

app.get('*', function (req, res) {
  const html = fs.readFileSync(path.resolve(__dirname, '../dist/index.html'), 'utf-8')
  res.send(html)
})
app.listen(8011);
console.log('success listen......');

二. 对vue脚手架的修改与页面的修改
我这里用的是vue封装的axios方法异步请求数据
下载axios,cnpm install axios
在main.js中引入axios并挂载到vue的原型链上(因为axios并不是vue的插件,如果不挂载,则需要每个组件中都要引入axios)
import axios from 'axios'
Vue.prototype.$http = axios

  1. 脚手架的修改。
    设置代理,在config文件夹中的index.js 把dev下的proxyTable修改为:
//这里的端口号设置为8011(服务的端口号)
proxyTable: {
      '/api': {
        target: 'http://localhost:8011/api/',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },
  1. 页面修改
    ①. 路由的修改
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Login from '@/components/Login'
Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/Login',
      name: 'Login',
      component: Login
    }
  ]
})

②. HelloWorld页面的修改
加一个router-link 指向login页面
③. login 页面的编写

<template>
    <div class="login">
        {{msg}}
        <div>
            用户名:
            <input type="text" v-model="name">
        </div>
        <div>
            密码:
            <input type="text" v-model="password">
        </div>
        <button @click="login">登录</button>
        <button @click="register">注册</button>
        <button @click="getAll">获得所有用户</button>
        <div v-show="showID">
            <p>用户id:{{nameId}}</p>
        </div>
        <div v-show="showAll">
            <p v-for="item in array">{{item.name}}的ID: {{item._id}} <button @click="deleteone(item.name)">删除该账号</button></p>
        </div>
    </div>
</template>
<script>
export default {
    name: "login",
    data(){
        return{
            msg: "登录注册",
            name: '',
            password: '',
            nameId: "",
            showID: false,
            array: [],
            showAll: false
        }
    },
    methods:{
        login(){
            this.showAll = false
            this.showID = false
            let params = {
                name: this.name,
                password: this.password
            }
            this.$http.post('/api/user/login',params).then((res)=>{
                console.log(res)
                if(res.data.status == 1000){
                   this.showID = true
                   this.nameId = res.data.data[0]._id
                }else{
                    alert(res.data.message)
                }
            }).catch((err)=>{
                console.log(err)
            })
        },
        register(){
            this.showAll = false
            this.showID = false
            let params = {
                name: this.name,
                password: this.password
            }
            this.$http.post('/api/user/register',params).then((res)=>{
                console.log(res)
                if(res.data.status == 1000){
                   alert(res.data.message)
                }else{
                    alert(res.data.message)
                }
            }).catch((err)=>{
                console.log(err)
            })
        },
        getAll(){
            this.$http.get('/api/user/all').then((res) => {
                console.log(res)
                if(res.data.length>0){
                    this.showAll = true
                    this.array = res.data
                }else{
                    alert("无注册用户!")
                }
            }).catch((err) => {
                console.log(err)
            })
        },
        deleteone(names){
            let params = {
                name: names
            }
            this.$http.post('/api/user/delete',params).then((res) => {
                console.log(res)
                this.array = res.data.data
            }).catch((err) => {
                console.log(err)
            })
        }
    }
}
</script>

至此 项目基本完成,没写样式什么的,看起来不好看,但是基本完成了登录注册的主要功能,如:登录,注册,查看所有注册用户,删除某一用户。
项目的github:https://github.com/zhaoxiang2018/mongodb-node-vue
下载后 自行配置下本地服务,
cnpm install
有可能报错 说让直行命令:npm install --save axios ,按他说的执行就好。
然后 npm run dev 打开前端服务
打开server文件夹cmd 执行 node index.js 打开node后台的服务

这样就可以在页面上进行注册登录啦!

相关文章

网友评论

      本文标题:MongoDB+node.js+experss+vue.js构建

      本文链接:https://www.haomeiwen.com/subject/hmrbiftx.html