您的位置:首页 > 其它

express随记01

2015-09-27 20:39 399 查看

系统变量的设置

app.get(env) | process.env.NODE_ENV
: 会自动判断当前环境类型;

app.get(port) | process.env.PORT
: 必须手动设置;

app.param([name], callback)

用来处理多个匹配

app.param('id', function (req, res, next, id) {
console.log('CALLED ONLY ONCE');
next();
})

app.get('/user/:id', function (req, res, next) {
console.log('although this matches');
next();
});

app.get('/user/:id', function (req, res) {
console.log('and this matches too');
res.end();
});

cookie

其默认值:
{ path: '/', httpOnly: true, secure: false, maxAge: null }


//注意获取和设置的不同

app.get('/', function (req, res) {
if (!req.cookies.counter)
res.cookie('counter', 0);
else
res.cookie('counter', parseInt(req.cookies.counter,10) + 1);
res.status(200).send('cookies are: ', req.cookies);
})


签名加密的
cookie


//会自动加密解密处理

app.use(cookieParser('test-sign'));
.........
app.get('/', function (req, res) {
if (!req.signedCookies.counter)
res.cookie('counter', 0, {signed: true});
else
res.cookie('counter', parseInt(req.signedCookies.counter,10) + 1, {signed: true});
res.status(200).send('cookies are: ', req.signedCookies);
})

session

//将session保存到redis中

var cookieParser = require('cookie-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);

app.use(cookieParser());
app.use(session({
resave: true,                             //是否强制保存session。即使没有被修改;
saveUninitialized: true,             //是否强制保存不是初始化的session;
name: 'connect.sid',                 //默认浏览器cookie保存的名称;
store: new RedisStore({
host: 'localhost',
port: 6379
}),
secret: '0FFD9D8D-78F1-4A30-9A4E-0940ADE81645',
cookie: { path: '/', maxAge: 3600000 }
}));

app.get('/', function(req, res){
console.log('Session ID: ', req.sessionID)
if (req.session.counter) {
req.session.counter = req.session.counter +1;
} else {
req.session.counter = 1;
}
res.send('Counter: ' + req.session.counter)
});


其中要控制的实效包括:
ttl
:
session
字段保存在数据库的实效;
maxAge
:
cookie
字段的有效时间;

如果设置
cookie secure: true
,那其只会在
https
session
才会去判断
cookie
值;

session
默认是
httpOnly:true


一般要将
saveUninitialized
设为
false
,避免未对
session
修改也被保存下来;

express-session
自带
debug
模式,运行时设置
DEBUG=express-session
开启;

一般流程

//登陆
login: fetching->no-session-found->[set]->saveing->split response->set-cookie
[redirect]-> fetching->session-found->touching->split response->touched
//重新打开
reopen: fetching->session-found->touching->touched
//退出
logout:  fetching->session-found->[set]->no-session->
[redirect]->fetching->no-session-found

全局参数

//两种形式

app.locals = {};
res.locals = {};

特殊的输出

设置头部

app.get('/set-csv', function(req, res) {
var body = 'title, tags\n' +
'Practical Node.js, node.js express.js\n' +
'Rapid Prototyping with JS, backbone.js node.js mongodb\n' +
'JavaScript: The Good Parts, javascript\n'
res.set({'Content-Type': 'text/csv',
'Content-Length': body.length,
'Set-Cookie': ['type=reader', 'language=javascript']});
res.end(body);
});


设置响应码

res.status(200).end();
res.status(200).send();
res.status(200).json();


数据流输出文件

app.get('/stream2', function(req, res) {
var stream = fs.createReadStream(largeImagePath);
stream.on('data', function(data) {
res.write(data);
});
stream.on('end', function() {
res.end();
});
});

app.get('/stream1', function(req, res) {
var stream = fs.createReadStream(largeImagePath);
stream.pipe(res);
});

服务器开关

var server = http.createServer(app);
var boot = function () {
server.listen(app.get('port'), function(){
console.info('Express server listening on port ' + app.get('port'));
}); };
var shutdown = function() {
server.close();
};

if (require.main === module) {
boot();
} else {
console.info('Running app as a module');
exports.boot = boot;
exports.shutdown = shutdown;
exports.port = app.get('port');
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: