系统变量的设置

  • 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,那其只会在httpssession才会去判断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');
}

express随记01的更多相关文章

  1. css随记01编辑技巧,背景与边框

    代码优化 一个按钮的例子,使其值同比例变化; button{ color: white; background: #58a linear-gradient(#77a0bb, #58a); paddin ...

  2. nodejs随记01

    EventEmitter var stream = require('stream'); var Readable = stream.Readable; //写入类(http-req就是),初始化时会 ...

  3. SpringBoot2.x-笔记(01)

    程序入口 @SpringBootApplication public class SpringbootApplication { public static void main(String[] ar ...

  4. PBOC规范研究

    一.ISO14443协议和PBOC关于CID的约定 看过协议的人其实都明白,RATS命令中参数字节的低半字节是CID,期中,CID不能为15. ISO14443协议中要求当RATS命令的CID等于0时 ...

  5. POS 60域用法

    版权声明:本文为博主原创文章,未经博主允许不得转载. 自定义域(Reserved Private) 1.变量属性 N...17(LLLVAR),3个字节的长度值+最大17个字节的数字字符域. 压缩时用 ...

  6. Express 教程 01 - 入门教程之经典的Hello World

    目录: 前言 一.Express?纳尼?! 二.开始前的准备工作 三.测试安装之经典的Hello World 四.使用express(1)来生成一个应用程序 五.说明 前言: 本篇文章是建立在Node ...

  7. [BI项目记]-TFS Express备份和恢复

    在项目中对TFS进行备份操作是日常重要的工作之一,此篇主要描述如何对TFS Express进行备份,并且在另外一台服务器上进行恢复. 以下是操作的几个关键点: 备份数据库,在TFS管理工具中就可以完成 ...

  8. NodeJS+express+mogondb学习笔记01

    0.准备工作  安装nodejs环境  官网地址:https://nodejs.org/en/  下载好了 直接一路安装 也没有什么可以说的 不得不说nodejs对于新手上手还是很友好的,再加上现在n ...

  9. nodejs弯路-01之'express' 不是内部或外部命令

    最近正想用node+angular+mongodb来完成一个小项目,三样都算是从零开始学习吧. 一开始是想用express -e projectname去创建一个ejs模板的项目.(一两句话就可以把大 ...

随机推荐

  1. code vs1517 求一次函数解析式(数论 纯数学知识)

    1517 求一次函数解析式  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 白银 Silver 题解  查看运行结果     题目描述 Description 相信大家都做过练 ...

  2. 重写Equals为什么要同时重写GetHashCode

    .NET程序员都知道,如果我们重写一个类的Equals方法而没有重写GetHashCode,则VS会提示警告 :“***”重写 Object.Equals(object o)但不重写 Object.G ...

  3. Centos7 设置Swap分区

    1.使用dd命令创建一个swap交换文件 dd if=/dev/zero of=/home/swap bs=1024 count=1024000 2.制作为swap格式文件: mkswap /home ...

  4. UIColor+Hex

    #import <UIKit/UIKit.h> @interface UIColor (Hex) + (UIColor *)colorWithHex:(long)hexColor;+ (U ...

  5. Codeforces Round #370 (Div. 2)(简单逻辑,比较水)

    C. Memory and De-Evolution time limit per test 2 seconds memory limit per test 256 megabytes input s ...

  6. redis配置详情

    # Redis configuration file example # Note on units: when memory size is needed, it is possible to sp ...

  7. 第一课 移动端&响应式

    一.调试工具介绍(Chrome Emulation) 1.Device(设备相关) 自定义尺寸.Network(网络模拟).UseAgent(浏览器信息).缩放 2.Media(媒体) 3.Netwo ...

  8. Loadrunner上传与下载文件脚本

    一. 上传脚本 Action() { int uploadImgStatus = 0; //获取上传产品图ID web_reg_save_param_ex("ParamName=imgRan ...

  9. 【翻译十二】java-并发之活性

    A concurrent application's ability to execute in a timely manner is known as its liveness. This sect ...

  10. Oracle 数组赋值

    只需要像下面这样就OK了 begin -- Call the procedure in_var(1):=null;in_var(1):='a123123'; pack_abc.pro_abc(in_v ...