Nodejs伺服器程式碼範例


var express = require('express');
var bodyParser = require('body-parser')
var app = express();
var uuid = require('uuid'); //自動產稱id的套件
var low = require('lowdb');
var db = low('db.json');
var session = require('express-session');
var moment = require('moment');

app.use(bodyParser.json());// 解析application/json
app.use(bodyParser.urlencoded({ extended: true }));//解析從網頁送來的資料
app.use(express.static('public'));
app.use(session({ secret: 'this is session' }));
app.set('view engine', 'ejs');

//初始化lowdb的db.json檔
db.defaults({ users: [] ,msgs:[]}).write();

//========================================================

app.get('/', function (req, res) {
    if (!req.session.user) {
        res.redirect("/login");
    } else {
        var msgs = db.get('msgs').orderBy('created_time','desc').value();
        //msgs送到前端錢可以用moment跟lodash更換時間格式......
        res.render('index', { user: req.session.user ,msgs:msgs});
    }
});

//========================================================

app.get('/login', function (req, res) {
    res.sendFile(__dirname + "/views/login.html");
});

//========================================================

app.post('/login', function (req, res) {

    var user =
        db.get('users')
            .find({ username: req.body.username })
            .value();

    if (user) {
        if (user.password == req.body.password) {

            // delete user.password
            req.session.user = user;

            res.send({
                code: 200,
                msg: "login successfully"
            });
        } else {
            res.send({
                code: 400,
                msg: "password is wrong"
            });
        }
    } else {
        res.send({
            code: 404,
            msg: "username is not existed",
        });
    }

});

//========================================================

app.post('/msg', function (req, res) {

    var newMsg =
        db.get('msgs')
            .push({"text":req.body.text,"username":req.session.user.username,created_time:new Date()})
            .last()
            .assign({ id: uuid() })
            .write();

    res.send({
        code:200,
        msg:"create new message successfully"
    });    

});

//========================================================

app.get('/logout', function (req, res) {
    delete req.session.user;
    res.redirect('/login');
});

//========================================================

app.get('/register', function (req, res) {
    res.sendFile(__dirname + "/views/register.html");
});

//========================================================

app.post('/register', function (req, res) {

    var user =
        db.get('users')
            .find({ username: req.body.username })
            .value();

    if (!user) {
        var newUser =
            db.get('users')
                .push(req.body)
                .last()
                .assign({ id: uuid() })
                .write();

        res.send({
            code: 200,
            msg: "register successfully"
        });
    } else {
        res.send({
            code: 409,
            msg: "username is alreay existed"
        });
    }
});

app.listen(3000, function () {
    console.log("伺服器跑起來啦!在你的瀏覽器網址列輸入 localhost:3000吧!");
});

results matching ""

    No results matching ""