Express+Socket.io實(shí)時(shí)投票系統(tǒng)(一)

通過實(shí)現(xiàn)一個(gè)Express和Socket.io的實(shí)時(shí)投票系統(tǒng)來(lái)學(xué)習(xí)Express和Socket.io的用法。

以下實(shí)現(xiàn)參考:http://www.ibm.com/developerworks/cn/web/wa-nodejs-polling-app/

構(gòu)建該應(yīng)用程序的先決條件:
1.基本了解 Node.js 和 Node.js 開發(fā)環(huán)境
2.具有以下這些 Node.js 模塊:Express frameworkJadeMongoosesocket.io
3.AngularJS JavaScript 框架
4.MongoDB NoSQL 數(shù)據(jù)庫(kù)

首先通過express-generator來(lái)創(chuàng)建一個(gè)新的工程

//安裝
npm install -g express-generator
//創(chuàng)建工程并進(jìn)入工程包
express poll && cd poll
//安裝依賴包
npm install

裝完以后,應(yīng)該就是一個(gè)express工程了
我們可以直接運(yùn)行一下

npm start

訪問
http://localhost:3000
就能看到Express生成的網(wǎng)站了。

安裝mongoose

//安裝mongodb依賴
npm install mongodb --save
//安裝mongoose依賴
npm install mongoose --save

安裝后,在poll工程下創(chuàng)建一個(gè)models文件夾,在這個(gè)文件夾下創(chuàng)建一個(gè)polls.js,這個(gè)文件定義了我們投票信息的結(jié)構(gòu)

'use strict'

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//投票IP
var voteSchema = new Schema({
    ip: String
});
//選項(xiàng)
var choiceSchema = new Schema({
    text: String,
    votes: [voteSchema]
});
//投票詳細(xì)信息
var pollSchema = new Schema({
    question: {
        type: String,
        required: true
    },
    choices: [choiceSchema],
    createdAt: {
        type : Date, 
        default: new Date()
    },
    updatedAt: {
        type: Date,
        default: new Date()
    }
});

module.exports = pollSchema;

結(jié)構(gòu)定義好之后,我們就可以寫對(duì)應(yīng)的增刪改查了
在routes/index.js中加入

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/demo2');

var pollSchema = require('../models/polls');
var Poll = mongoose.model('Poll', pollSchema);

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

//投票列表
router.get('/polls', function(req, res, next){
    Poll.find({}, 'question', function(error, polls){
        res.json(polls);
    })
});

//取得單一投票信息
router.get('/poll/:id', function(req, res, next){
    var pollId = req.params.id;

    Poll.findById(pollId, '', {lean: true}, function(error, poll){
        //查詢單條投票信息
        if(poll){
            var userVoted = false,
                userChoice,
                totalVotes = 0;
            poll.choices.forEach(function(choice, index) {
                choice.votes.forEach(function(vote, index) {
                    totalVotes++;
                    if(vote.ip === (req.header('x-forwarded-for') || req.ip)){
                        userVoted = true;
                        userChoice = { _id: choice.id, text: choice.text };
                    }
                });
            });
            poll.userVoted = userVoted;
            poll.userChoice = userChoice;
            poll.totalVotes = totalVotes;
            res.json(poll);
        }else{
            res.json({error: true});
        }
    });

});

//創(chuàng)建投票
router.post('/pollAdd', function(req, res, next){
    var reqBody = req.body;
    var choices = reqBody.choices.filter(function(v){
        return v.text != "";
    });
    var pollObj = {
        question: reqBody.question,
        choices: choices
    }
    var poll = new Poll(pollObj);
    poll.save(function(error, doc){
        if(error || !doc){
            res.send(error);
        }else{
            res.json(doc);
        }
    })
});

這里定義了兩個(gè)Get方法,一個(gè)Post方法,兩個(gè)Get方法主要是獲取數(shù)據(jù),一個(gè)是獲取列表,一個(gè)是獲取單一投票信息的方法,這里Restful接口就定義好了
現(xiàn)在運(yùn)行一下

npm start

你可以用一些Post工具,直接插入數(shù)據(jù),個(gè)人比較喜歡用Postman
這里可以往http://localhost:3000/pollAdd發(fā)送Post請(qǐng)求

{
    "question": "question1",
    "choices": [{ "text": "choices1"}, { "text": "choices2"}, { "text": "choices3"}]
}
屏幕快照 2016-10-27 下午4.34.12.png

如果沒有報(bào)錯(cuò)的話,數(shù)據(jù)就插入mongodb數(shù)據(jù)庫(kù)了。
好了,第一節(jié)結(jié)束了。休息一下,下面第二節(jié)的話,會(huì)介紹Angular的安裝

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容