从零开始 node + MongoDB 搭建服务器

前言

纯前端开发,零后端基础,记录第一次搭建服务器

准备

  1. node + express 4.x
  2. MongoDB 3.4 + mongoose 4.10.8

安装nodejs、mongodb

https://nodejs.org/en/
https://www.mongodb.com/download-center

配置 MongoDB

配置成window服务,添加目录

-config //配置文件目录
  -mongodb.cfg
-db //数据目录
-log //日志目录

mongodb.cfg

systemLog:  //日志配置
    destination: file  //日志输出目的地,可以指定为“ file”或者“syslog”
    path: D:\MongoDB\data\log\mongod.log
    logAppend: true  //当mongod/mongos重启后是否在现有日志文件添加日志
storage:
    journal:
        enabled: true  //是否开启journal日志持久存储
    dbPath: D:\MongoDB\data\db
net:
    port: 27017 //mongod/mongos侦听端口,默认为27017

安装服务

cd 到 D:\MongoDB\Server\3.4\bin
D:\MongoDB\Server\3.4\bin> ./mongod.exe --config "D:\MongoDB\data\config\mongod.cfg" --install

启动mongodb服务

net start MongoDB

新建工程

- yarn add express    //安装express
- cd到指定的目录       //更改路径
- express -e xxx      //创建工程,e为ejs模版,xxx为文件夹名

安装必要插件,packge.json 如下

{
  "name": "server",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "^1.17.2",
    "debug": "^2.6.8",
    "ejs": "^2.5.6",
    "express": "^4.15.3",
    "file-stream-rotator": "^0.1.0",
    "mongoose": "4.10.8",
    "morgan": "^1.8.2",
    "serve-favicon": "^2.4.3"
  }
}

文件目录

-bin
-config //配置文件    
  -mongoose.js
-logs //生成日志文件
-models         
-public //静态资源
-routes //路由模块
  -index.js
-utils //自定义中间件
-views //模版文件夹
  -index.html
-app.js //入口文件
-package.json

app.js

var express = require('express');

var path = require('path');
var favicon = require('serve-favicon');

var logger = require('morgan');

var fs = require('fs');
var FileStreamRotator = require('file-stream-rotator');

var bodyParser = require('body-parser');

var mongoose = require('./config/mongoose');

var db = mongoose();

/********* 引入路由模块 *********/
var routes = [
  {name: 'index', route: require('./routes/index')},
  //{name: 'users', route: require('./routes/users')}
]

var app = express();

/********* 日志设置 *********/
var logDirectory = __dirname + '/logs'
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)
// create a rotating write stream
var accessLogStream = FileStreamRotator.getStream({
  filename: logDirectory + '/access-%DATE%.log',
  frequency: 'daily',
  verbose: false
})
// 生成日志文件
app.use(logger('combined', {stream: accessLogStream}))
// 打印到控制台
app.use(logger('common', {stream: accessLogStream}))

/********* 跨域访问 *********/
app.all('*', function(req, res, next) {  
    res.header('Access-Control-Allow-Origin', '*');  
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');  
    res.header('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,OPTIONS');  
    res.header('X-Powered-By',' 3.2.1')  
    res.header('Content-Type', 'application/json;charset=utf-8');  
    next();  
});

/********* 模版引擎 *********/
  app.set('views',path.join(__dirname , 'views') );
  app.engine('.html', require('ejs').__express);  
  app.set('view engine', 'html');

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname, 'public')));

routes.forEach(function(item) {
  app.use('/'+item.name, item.route)
})

module.exports = app;

config/mongoose.js

var mongoose = require('mongoose');
mongoose.Promise = global.Promise

module.exports = function() {
    var db = mongoose.connect('mongodb://localhost:27017/mongoose-test' , {}, function (err, res) {
        if (err) { 
            console.log('Connection refused to mongodb://localhost:27017/mongoose-test');
            console.log(err);
        } else {
            console.log('Connection successful to mongodb://localhost:27017/mongoose-test');
        }
    });
    //require('../models/users.js');
    return db;
}

routes/index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

views/index.html

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

启动服务器

node ./bin/www

在浏览器中输入 http://localhost:3000/index

你可能感兴趣的:(从零开始 node + MongoDB 搭建服务器)