返回列表

极简 express node server 附: 工程级项目结构

默认分类 2016/03/02 02:51

app.js

'use strict';

var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var Formidable = require('formidable');
var Session = require('express-session');
var UUID = require('uuid');

var app = express();
var port = 3000;

app.use(cookieParser());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());

app.use(express.static(__dirname + '/public'));

app.use(Session({
    genid: function(req) {
        return UUID.v1(); // use UUIDs for session IDs
    },
    cookie: {
        maxAge: 60000
    },
    secret: 'keyboard cat',
    resave: true,
    saveUninitialized: true
}));

app.use('/session', function(req, res, next) {
    var sess = req.session;
    if (sess.views) {
        sess.views++;
        res.setHeader('Content-Type', 'text/html');
        res.write('<p>views: ' + sess.views + '</p>');
        res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
        res.end();
    } else {
        sess.views = 1;
        res.end('welcome to the session demo. refresh!');
    }
});

app.all('*', function(req, res, next) {
    console.log('req.url: ' + req.url);
    next();
});
app.all('/?', function(req, res) {
    res.send('Hi');
});
app.all('/hi', function(req, res) {
    res.send('Hi world');
});

app.all('/test/:id', function(req, res) {
    var result = {
        cookie: req.cookie,
        params: req.params,
        query: req.query,
        body: req.body
    };

    res.send(result);
});


app.post('/file', function(req, res) {
    var form = new Formidable.IncomingForm();
    form.uploadDir = './public';
    form.keepExtensions = true;

    form.parse(req, function(err, fields, files) {
        console.log(fields);
        console.log(files);

        res.send('ok');
    });
});

var server = app.listen(port, function() {
    console.log('Example app listening at http://0.0.0.0:%s', port);
});

在app.js同级目录新建一个叫public的文件夹;

别忘了 node_modules:

npm install express cookie-parser body-parser formidable express-session uuid

附: NodeJS工程级项目结构