系统变量的设置

  • 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. DB2用一张表更新其他表的数据

    表结构: CREATE TABLE ATEST  (ID    INTEGER,   NAME  VARCHAR(256),   CODE  INTEGER,   NAME2 VARCHAR(256) ...

  2. jsp页面路径问题

    jsp路径默认不是项目跟路径 一. <%@ page language="java" import="java.util.*" pageEncoding= ...

  3. tomcat URL乱码问题

    用get传参时,显示乱码 在tomcat里的server.xml中添加一下即可. <Connector port="8080" protocol="HTTP/1.1 ...

  4. 【leetcode】 Generate Parentheses (middle)☆

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  5. 【linux】进程不要开太多,否则系统会卡死!

    今天在跑一个任务,大概像下面这样 python task.py -s input/ input文件夹下有两百多个文件,比如1.txt, 2.txt等等,task.py会顺序读取并做操作. 我想,这不是 ...

  6. 点击按钮出现60秒倒计时js代码

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  7. db2 Hidden columns

    When a table column is defined with the implicitly hidden attribute, that column is unavailable unle ...

  8. web storm

    常用插件: code glance 代码预览功能,用过的都知道有多爽...

  9. jQuery - 4.简单选择器

    4.1 简单选择器   (1) :first 选取第一个元素.   (2) :last 选取最后一个元素.  (3) :not(选择器) 选取不满足"选择器"条件的元素   (4) ...

  10. Ubuntu下调整swap分区的大小

    转自:http://blog.chinaunix.net/uid-7573623-id-2048964.html 由于安装oracle 的时候,swap太小不能继续安装,于是想有什么方法在不不用安装o ...