开始nodejs+express的学习+实践(8)
1.session使用
介绍的非常详细: http://www.cnblogs.com/chenchenluo/p/4197181.html
对比我们的app.js需要引入express-session模块和使用这个模块,在package依赖,并加载。
我们修改app.js
我们既然有了session,我们开始测试使用,在访问首页我们就是设置session内容,当我们跳转时,比如到hello,我们是还能访问到设置session的值,这就表示session安装成功。
index.js对首页和hello修改,加入session赋值
app.get('/',function(req, res){ var currentpage=req.query.currentpage?req.query.currentpage:1; model.model_index(currentpage,function(items,len,allpage){ req.session.love = '我爱你'; res.render('index', { title: 'Express',hello: 'hello world!',arr: items,len:len,allpage:allpage,cur:currentpage,love: req.session.love }); }); }); app.get('/hello', function(req, res){ var currentpage=req.query.currentpage?req.query.currentpage:1; model.model_hello(currentpage,function(items){ res.render('hello', { arr: items,love: req.session.love }); }); });
在index.html和hello.html显示session内容:
<h1><%= love %></h1>
我们访问首页和hello:
我们在访问首页,会给session赋值,当我们跳到hello页面,,req对象的session值我们还是可以拿到,所以就在hello页面可以显示了。
用途最常用的就是我们登陆后其他页面登录信息的显示。
session是安装很简单,加载模块,设置参数就可以使用了,删除session我们就可以对
req.session.con=null的设置就ok了。
index.js修改如下:
var formidable = require('formidable'); var fs = require('fs'); var crypto = require('crypto'); var model = require('../model/model'); function rout(app){ app.get('/',function(req, res){ var currentpage=req.query.currentpage?req.query.currentpage:1; model.model_index(currentpage,function(items,len,allpage){ req.session.love = '我爱你'; res.render('index', { title: 'Express',hello: 'hello world!',arr: items,len:len,allpage:allpage,cur:currentpage,love: req.session.love }); }); }); app.get('/hello', function(req, res){ var currentpage=req.query.currentpage?req.query.currentpage:1; model.model_hello(currentpage,function(items){ res.render('hello', { arr: items,love: req.session.love }); }); }); app.get('/hellomore', function(req, res){ model.model_hello(req.query.more,function(items){ res.send(items); }); }); app.get('/list', function(req, res){ res.render('list', { text: req.query.id }); }); app.get('/login', function(req, res){ res.render('login'); }); app.post('/logincheck', function(req, res){ var user= req.body.user; var pass= req.body.pass; if(user=="tom" && pass=="tom"){ res.redirect('/'); }else{ res.redirect('/login'); }; }); app.get('/file', function(req, res){ res.render('file'); }); app.post('/upfile', function(req, res){ //code var form = new formidable.IncomingForm(); form.uploadDir = "./upload"; form.parse(req, function(err, fields, files) { if (err) { res.redirect('/file'); } var tmp_path, target_path; if (files.file.size > 0) { //表示有文件上传 tmp_path = files.file.path;//内存中的文件,当前文件目录 var picType = files.file.name.split(".")[1];//后缀名 //移动目的目录 target_path = './public/images/pic_1.' + picType; //同步方式移动文件 fs.renameSync(tmp_path, target_path); }else{ res.redirect('/file'); }; }); }); app.get('/fs', function(req, res){ fs.writeFile('./fs/me/1.txt', 'read me','utf8', function (err) { if (err) throw err; }); }); app.get('/crypto', function(req, res){ var pass="admin"; var md5 = crypto.createHash('md5'); var mpass=md5.update(pass).digest('hex'); var rmpass=mpass.substring(2); res.render('crypto', { res:pass,resm:mpass,resrm:rmpass }); }); app.get('/globals', function(req, res){ res.render('globals', { res:__dirname+":"+__filename }); }); }; exports.rout=rout;
app.js的修改:
var express = require('express'); var http = require('http'); var path = require('path'); var favicon = require('static-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var session = require('express-session'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var users = require('./routes/user'); var app = express(); // view engine setup app.engine('html', require('ejs').renderFile); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'html'); app.use(favicon()); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); app.use(session({ secret: '12345', name: 'testapp', //这里的name值得是cookie的name,默认cookie的name是:connect.sid cookie: {maxAge: 80000 }, //设置maxAge是80000ms,即80s后session和相应的cookie失效过期 resave: false, saveUninitialized: true, })); app.use(express.static(path.join(__dirname, 'public'))); app.use(app.router); routes.rout(app); app.get('/users', users.list); /// catch 404 and forwarding to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); /// error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.render('error', { message: err.message, error: {} }); }); module.exports = app;
package.json
{ "name": "application-name", "version": "0.0.1", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "express": "~3.4.8", "static-favicon": "~1.0.0", "morgan": "~1.0.0", "cookie-parser": "~1.0.1", "body-parser": "~1.0.0", "debug": "~0.7.4", "ejs": "~0.8.5", "formidable": "*", "mongodb":"*", "mongoskin":"*", "express-session":"*" } }
2.总结
到这里关于nodejs+express的学习和实践就几乎结束了,
当然一个网站一般会有下面功能:
注册
登录
数据显示
数据添加,修改,删除等等等
我们在分页那里学了数据的查询,其他的都算是类似处理,自己摸索就可以了,
还有登录的操作,其实session就是为登陆后使用的,前面文件上传操作也是为头像做基础的,验证码也是要在session设置和判断,加密模块的学习就是对注册密码和登录密码的处理,很多很多处理吧,那都不属于入门的了,不在做学习和实践介绍了。
下一篇就是爬虫抓取的介绍,最简单的操作一次。