npm在package.json文件中管理項(xiàng)目的依賴(lài)項(xiàng)以及項(xiàng)目的元數(shù)據(jù)。要?jiǎng)?chuàng)建這個(gè)文件,最簡(jiǎn)單的辦法是運(yùn)行npm init:它會(huì)問(wèn)一系列的問(wèn)題,然后為你生成一個(gè)package.json文件幫你起步滋觉,如下圖
安裝express:
npm install --save express
(--save用于更新package.json)
因?yàn)閚ode_modules隨時(shí)都可以用npm重新生成,所以我們不會(huì)把這個(gè)目錄保存在我們的代碼庫(kù)中
創(chuàng)建一個(gè).gitignore文件:
# ignore packages installed by npm
node_modules
# put any other files you don't want to check in here,
# such as .DS_Store (OSX), *.bak, etc.
創(chuàng)建配置文件config.js:
創(chuàng)建入口文件server.js:
var app = require('express')();
//配置文件
var config = require('./config.js');
//禁用Express的X-Powered-By頭信息
app.disable('x-powered-by');
//添加通用中間件
//請(qǐng)求體中間件
app.use(require('body-parser')());
//靜態(tài)資源目錄(存放css、js、圖片文件等靜態(tài)資源)
app.use(express.static(__dirname +'/public'));
//設(shè)置端口號(hào)(如果配置了環(huán)境端口,會(huì)優(yōu)先選擇)
app.set('port', process.env.PORT || config.port);
//視圖模版設(shè)置
var handlebars=require('express-handlebars').create({
defaultLayout:'main',//默認(rèn)公共模版
extname:'.hbs',//文件后綴名
helpers:require('./helper.js').helpers()//輔助函數(shù)
});
app.engine('hbs',handlebars.engine);
app.set('view engine','html');
//監(jiān)聽(tīng)端口
app.listen(app.get('port'),function(){
console.log('Express started on http://localhost:'+app.get('port') +'; press Ctrl-C to terminate.');
});
//如果需要使用子域名荠呐,可以使用vhost(npm install --save vhost)
//創(chuàng)建子域名"admin"......它應(yīng)該出現(xiàn)在所有其他路由之前varadmin = express.Router();
app.use(vhost('admin.*', admin));
//創(chuàng)建admin的路由;它們可以在任何地方定義admin.get('/',function(req, res){
res.render('admin/home');
});
admin.get('/users',function(req, res){
res.render('admin/users');
});
//路由分組
require('./routers.js')(app);
// 定制404頁(yè)面
app.use(function(req, res){
res.type('text/plain');
res.status(404);
res.send('404 - Not Found'+config.name);
});
// 定制500頁(yè)面
app.use(function(err, req, res, next){
console.error(err.stack);
res.type('text/plain');
res.status(500);
res.send('500 - Server Error');
});
創(chuàng)建路由分組文件routers.js:
默認(rèn)忽略了大小寫(xiě)或反斜杠,并且在進(jìn)行匹配時(shí)也不考慮查詢(xún)字符串
//引入控制器
var home = require('./controllers/home.js');
var about = require('./controllers/about.js');
//提供接口
module.exports = function(app){
//home
app.get('/',home.home);
//about
app.get('/about',about.about)
//帶參數(shù)的路由
app.get('/abou/:city/:name',about.city);
//正則表達(dá)式路由
1.用同一個(gè)路由處理/和/home
app.get('/(home)?, home.home');
2.完整的正則表達(dá)式
app.get(/crazy|mad(ness)?|lunacy/,function(req,res){});
//因?yàn)槁酚傻谋举|(zhì)也是中間件邓厕,所以還可以這樣寫(xiě)
app.get('/about',function(req,res,next){
if (...) return next();//走向下一個(gè)中間件炫惩,這里就是about.about
return res.send('...');//結(jié)束返回昔园,不會(huì)向下走蔓榄,render,json一樣
}, about.about);
}
創(chuàng)建控制器文件home.js蒿赢、about.js:
exports.home = function(req,res,next){
res.render('home', {
title: '主頁(yè)',//傳遞參數(shù)
layout:null,//不使用默認(rèn)模版
//還可以重寫(xiě)輔助方法...
})
}
exports.about = function(req,res,next){...}
創(chuàng)建數(shù)據(jù)庫(kù)主文件db.js:
npm install --save mongoose
var mongoose=require('mongoose');
var config=require('../config.js');
//連接數(shù)據(jù)庫(kù)
mongoose.connect(config.db,{server: {poolSize:20, socketOptions:{keepAlive:1}}},function(err) {if(err) {process.exit(1);}});
require('./admin/coal');
exports.Coal=mongoose.model('Coal');//導(dǎo)出模型
...
//如果使用云托管润樱,MongoLab:https://npmjs.org/package/mongodb
然后將數(shù)據(jù)庫(kù)憑證添加到config.js文件里:
mongo: {
development: {connectionString: 'your_dev_connection_string',},
production: {connectionString: 'your_production_connection_string',},
}
//連接
var opts = {server: {socketOptions: { keepAlive: 1 }}};
switch(app.get('env')){
case 'development':
mongoose.connect(credentials.mongo.development.connectionString, opts);break;
case 'production':
mongoose.connect(credentials.mongo.production.connectionString, opts);break;
default:throw newError('Unknown execution environment: ' + app.get('env'));
}
創(chuàng)建模型文件:
var helper=require('../helper.js');//封裝數(shù)據(jù)庫(kù)公共方法
var mongoose=require('mongoose');
var CoalSchema=new mongoose.Schema({
supplier: String,
water: {type:String,default:'123'//默認(rèn)值}
});
CoalSchema.statics.getCoal=function(callback){this.find(callback);}
//導(dǎo)出
module.exports=mongoose.model('Coal',CoalSchema);
不寫(xiě)了渣触,太多了羡棵。。嗅钻。