Node.js 에서 Redis Session을 사용하는 예제
Node.js 에서 Redis Session을 사용하는 단순한 예제.
Use Redis Session in node.js
var express = require('express'); var router = express.Router(); var path = require('path'); var favicon = require('serve-favicon'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var http = require('http'); var expressSession = require('express-session'); var fs = require('fs'); var RedisStore = require('connect-redis')(expressSession); var redis = require('redis'); var app = express(); //http//////////////////////////////// var httpServer=http.createServer(app); httpServer.listen(80, function(){ console.log("http server listening on port " + 80); }); //////////////////////////////// app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); var redisConfig = { "host": "localhost", "port": 6379, "prefix": "session:", "db": 0, "client": redis.createClient(6379,"localhost") } const session = expressSession({ secret : new Date().getMilliseconds()+"brokim", resave : false, store : new RedisStore(redisConfig), saveUninitialized:true, cookie : { maxAge : 1000 * 60 * 3 } }); app.use(session); app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(express.static(path.join(__dirname, 'public'))); app.get('/',function(req,res){ fs.readFile('./public/login/index.html', function(error, data) { if(error != undefined) { console.log(error); res.writeHead(404); res.end(); } else { res.writeHead(200, {'Content-Type': 'text/html'}); res.end(data); } }); }); ////////////////////////////////////////////////////////////////////////////////// /////////////////RESTFUL APIS///////////////////////////////////////////////////// //LOGIN/////////////////////////////////////////////////////////////////////////// app.route('/login') .post(function login_post(req,res){ try{ //query는 따로 구현하면 됨. //var query = require('./query.js'); query.login([ req.body.id ,salted(req.body.pw)], function loginAPI(ret){ if(ret.fail==0){ req.session.privilege=ret.result.privilege; req.session.uid=ret.result.id; req.session.name=ret.result.name; } res.send(ret); }); } catch(error){ } }); app.get('/logout', function logout_get(req,res){ req.session.destroy(function logout_destroy(err){ if(err!==null){ RESULT.GENERAL_FAIL.result=""; res.send(RESULT.GENERAL_FAIL); } else { RESULT.GENERAL_SUCCESS.result=""; res.send(RESULT.GENERAL_SUCCESS); } }); }); module.exports = app;
0 개의 댓글:
댓글 쓰기