node ch.08 _ Routing 모듈화2 (DB연결)
-
/form 으로 접근해서 처리하는 작업을 router로 분리
-
/router/email.js 파일 생성
-
app.js 에서 두 가지 방식으로 post 처리했던 코드 가져오기 & 수정
email.js 에 입력
var express = require('express') var app = express() var router = express.Router() var path = require('path') router.post('/form', function(req,res){ console.log(req.body.email) res.render('email.ejs', {'email' : req.body.email}) }) router.post('/ajax', function(req, res){ var email = req.body.email; var responseData = {}; var query = connection.query('select name from user where email="' + email + '"', function (err, rows) { if (err) throw err; if (rows[0]) { console.log(rows[0]) responseData.result = "ok"; responseData.name = rows[0].name; } else { responseData.result = "none"; responseData.name = ""; } res.json(responseData) }) }) module.exports = router;
-
form.html 수정
<html> <head> <meta charset="utf-8"> <title>email form</title> </head> <body> <form action="/email/form" method="post"> email : <input type="text" name="email"> <br/> <input type="submit"> </form> <button class="ajaxsend">ajaxsend</button> <div class="result"></div> <script> document.querySelector('.ajaxsend').addEventListener('click', function() { var inputdata = document.forms[0].elements[0].value; sendAjax('http://127.0.0.1:3000/email/ajax',inputdata); }) function sendAjax(url, data){ var data = {'email' : data}; data = JSON.stringify(data); var xhr = new XMLHttpRequest(); xhr.open('POST', url); xhr.setRequestHeader('Content-Type', "application/json"); //서버로 json형태로 보낸다는걸 나타내주기위해 xhr.send(data); xhr.addEventListener('load', function(){ //console.log(xhr, responseText); var result = JSON.parse(xhr.responseText); var resultDiv = document.querySelector(".result"); if(result.result !== "ok") resultDiv.innerHTML = "Your email is not found" else resultDiv.innerHTML = result.name; }); } </script> </body> </html>
-
위 까지 수정해 주면 email.ejs로 실행되는 ‘제출’ 버튼은 정상 작동함
결과확인 » ‘제출’ 버튼 클릭
-
ajax send 작동을 위해서 app.js에 DB connecttion 부분과 mysql 선언부분을 email.js 에 입력
email.js
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.post('/form', function(req,res){ console.log(req.body.email) res.render('email.ejs', {'email' : req.body.email}) }) router.post('/ajax', function(req, res){ var email = req.body.email; var responseData = {}; var query = connection.query('select name from user where email="' + email + '"', function (err, rows) { if (err) throw err; if (rows[0]) { console.log(rows[0]) responseData.result = "ok"; responseData.name = rows[0].name; } else { responseData.result = "none"; responseData.name = ""; } res.json(responseData) }) }) module.exports = router;
app.js
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var main = require('./router/main'); var email = require('./router/email'); 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('/main', main) app.use('/email', email) app.get('/', function(req,res){ console.log('test'); res.sendFile(__dirname + "/public/main.html") })
-
결과 확인 » ajaxsend 버튼 클릭