node+vue+MongoDB从构建项目到服务器部署
发布于 12 天前 作者 474782977 438 次浏览 来自 分享

用到技术:node-vue-vuex-axios-es6/es7-mongodb 记录一下项目从无到有到服务器部署 Centos 6 MongoDB 3.2.7

一、利用vue-cli构建项目: 1、安装vue-cli至全局

 npm install -g vue-cli

2、使用vue-cli初始化项目:

 vue init webpack-simple node-vue-demo

3.安装依赖:

npm install

4.运行项目:

npm run dev

二、启动node服务及安装mongodb 1.在项目文件夹下创建server文件夹放node代码 2.在server文件夹下创建app.js

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);

// 静态文件
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.all('*',function (req, res, next) {
	console.log(req,res)
	res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

// 监听80端口
app.listen(80);
console.log('server is running 80');

3.创建api.js

"use strict";
const models = require('./db');
const express = require('express');
const router = express.Router();

// 创建账号
router.post('/api/login/createAccount',(req,res) => {
    let newAccount = new models.Login({
        account : req.body.account,
        password : req.body.password
    });
    newAccount.save((err,data) => {
        if (err) {
            res.send(err);
        } else {
            res.send('Create success');
        }
    });
});

// 获取全部账号
router.get('/api/login/getAccount',(req,res) => {
    // 查找数据库
    models.Login.find((err,data) => {
        if (err) {
            res.send(err);
        } else {
            res.send(data);
        }
    });
});

module.exports = router;

5.安装下载并安装mongodb(linux安装方法)

这里我们在官网下载源码进行安装. 下载地址: https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel62-3.2.7.tgz

使用wget下载

cd /usr/local
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel62-3.2.7.tgz
tar -xvf mongodb-linux-x86_64-rhel62-3.2.7.tgz
mv mongodb-linux-x86_64-rhel62-3.2.7 mongodb
配置环境变量

修改/etc/profile, 添加如下内容

export MONGODB_HOME=/usr/local/mongodb
export PATH=$MONGODB_HOME/bin:$PATH
执行命令:
vim /etc/profile
source /etc/profile

查看mongodb版本信息 mongod -v


启动

创建数据库目录

MongoDB需要自建数据库文件夹.
mkdir -p /data/mongodb
mkdir -p /data/mongodb/log
touch /data/mongodb/log/mongodb.log
添加配置文件
新建mongodb.conf配置文件, 通过这个配置文件进行启动.
vim /etc/mongodb.conf
配置文件内容:
dbpath=/data/mongodb
logpath=/data/mongodb/log/mongodb.log
logappend=true
port=27017
fork=true
##auth = true # 先关闭, 创建好用户在启动

通过配置文件启动
mongod -f /etc/mongodb.conf
about to fork child process, waiting until server is ready for connections.
forked process: 2814
child process started successfully, parent exiting
出现successfully表示启动成功了.

进入 MongoDB后台管理 Shell
cd /usr/local/mongodb/bin
./mongo
创建数据库

use test
switched to db test
创建成功.

创建用户, 设置权限
db.createUser(
    {
        user: "test",
        pwd: "test",
        roles: [ { role: "readWrite", db: "test" } ]
    }
)

4.连接mongodb

const mongoose = require('mongoose');
// 连接数据库
mongoose.connect("mongodb://admin:Password@172.0.0.1:27017/admin",{useMongoClient:true});
//如没有创建用户则:"mongodb://172.0.0.1:27017/test

const db = mongoose.connection;
db.once('error',() => console.log('Mongo connection error'));
db.once('open',() => console.log('Mongo connection successed'));

const loginSchema = mongoose.Schema({
    account : String,
    password : String
});


const Models = {
    Login : mongoose.model('Login',loginSchema)
}

module.exports = Models;

5.启动node服务

node  /server/app.js

6.vue调用node服务

<template>
  <div class="hello">
    <img src="../assets/logo.png">
    <h2>Hello</h2>
    <div>
      <p>账号:<input type="text" v-model='account'></p>
      <p>密码:<input type="text" v-model='password'></p>
      <button @click='login'>创建</button>
      <button @click='query'>查看创建</button>
    </div>
    <ul>
      <li style="display:block;" v-for="(val, key) in list">
        <span>用户名:{{val.account}}密码:{{val.password}}</span>
      </li>
    </ul>
  </div>
</template>

<script>
import http from "./../lib/http";
import apiUrl from "./../lib/ApiSetting";
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      account:'',
      password:'',
      list:{}
    }
  },
  created() {
     
  },
  methods: {
    login(){
      if(this.account&&this.password){
        http(apiUrl.createAccount,
          {
            account:this.account,
            password:this.password
          })
        .then((res)=>{
          alert('创建成功')
        })
      }
    },
    query(){
      http(apiUrl.getAccount)
      .then((res)=>{
        console.log(res.data)
        this.list = res.data
      })
    }
  }

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>

三、node服务常驻linux系统

$ sudo npm install forever -g   #安装
$ forever start ./server/app.js          #启动
$ forever stop ./server/app.js         #停止
$ forever start -l forever.log -o out.log -e err.log ./server/app.js   #输出日志和错误
//此次有个小坑,如果进入server里面运行app.js会提示未找到模块

部署完成 GitHub地址:https://github.com/474782977/node-vue

回到顶部