node ch.12 _ Passport 환경구축
세션 - 세션값 서버에 저장하기
-
/join/index.js 에서 join.html로 연결되었던 부분을 join.ejs 템플릿을 사용하도록 수정
res.render() 함수 사용
var express = require('express') var app = express() var router = express.Router() var path = require('path') var mysql = require('mysql') // DATABASE SETTING (Google Cloud SQL) var connection = mysql.createConnection({ host : '35.189.176.97', port : 3306, user : 'root', password : 'root', database : 'jsman' }); connection.connect(); router.get('/', function(req,res){ //res.sendFile(path.join(__dirname, '../../public/join.html')) res.render('join.ejs'); }) router.post('/', function(req,res){ var body = req.body; var email = body.email; var name = body.name; var passwd = body.password; var sql = {email : email, name : name, password : passwd}; var query = connection.query('insert into user set ?', sql, function(err, rows) { if(err) { throw err;} //console.log("Data inserted!", rows.insertID, name); res.render('welcome.ejs', {'name' : name, 'id': rows.insertId}) }) }) module.exports = router;
-
/views/join.ejs 파일 생성
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>JOIN</title> <style> .messages{ color : #963b3b; margin-bottom: 16px; } </style> </head> <body> <h1>Join my website! </h1> <section class="messages"> </section> <form action="/join" method="post"> email : <input type="text" name="email"><br> password : <input type="text" name="password"><br> <input type="submit"> </form> </body> </html>
-
/join/index.js 에서 router.post() 부분에서 post형식으로 데이터를 처리해 주던 것을 passport를 이용하여 처리해 보자
-
passport 모듈 설치
$ npm install passport passport-local express-session connect-flash --save-dev
-
app.js 수정 (설치한 모듈 추가)
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var router = require('./router/index'); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var session = require('express-session'); var flash = require('connect-flash'); app.listen(3000, function() { console.log("start@ on port 3000"); }); app.use(express.static('public')) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({extended:true})) app.set('view engine', 'ejs') app.use(router)
-
passport 구현에 사용된 모듈 정리
참고: http://passportjs.org/docs/overview
-
passport
-
passport-local
-
express-session
-
flash
-