node ch.10 _ DB에 데이터 추가
Express 에서 MySQL에 새로운 데이터를 추가하기 (회원가입 페이지 구현)
Get 방식으로 join 페이지 나타내기
-
/router/join/index.js < join 경로를 생성하고 index.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.get('/', function(req,res){ console.log('get join url') res.sendFile(path.join(__dirname, '../../public/join.html')) }) module.exports = router;
-
/public/join.html 파일 생성
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JOIN</title> </head> <body> <h1>Join my website! </h1> <form action="/join" method="post"> email : <input type="text" name="email"><br> name : <input type="text" name="name"><br> password : <input type="text" name="password"><br> <input type="submit"> </form> </body> </html>
-
/router/index.js 파일에 join 라우팅
var express = require('express') var app = express() var router = express.Router() var path = require('path') var main = require('./main/main') var email = require('./email/email') var join = require('./join/index') router.get('/', function(req,res){ console.log('indexjs . path loaded'); res.sendFile(path.join(__dirname + "/../public/main.html")) }); router.use('/main', main) router.use('/email', email) router.use('/join', join) module.exports = router;
-
결과 확인
POST 방식으로 데이터 입력 받아와서 DB에 insert
-
/router/join/index.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.get('/', function(req,res){ res.sendFile(path.join(__dirname, '../../public/join.html')) }) router.post('/', function(req,res){ var body = req.body; var email = body.email; var name = body.name; var passwd = body.password; var query = connection.query('insert into user (email, name, password) values ("' + email + '","' + name + '","' + passwd + '")', function(err, rows) { if(err) { throw err;} console.log("Data inserted!"); }) }) module.exports = router;
-
실행 결과
email, name, password 항목 입력 후 제출 클릭
DB에 제대로 insert 되었는지 확인