고병후

Connect database

<회원 정보>
CREATE TABLE tunnel.users(
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
pw VARCHAR(30) NOT NULL,
personality CHAR(4) NOT NULL,
status TINYINT NOT NULL,
PRIMARY KEY(id),
UNIQUE INDEX name_UNIQUE (name ASC)
)
COMMENT = 'user information'
DEFAULT CHARACTER SET = utf8
ENGINE = InnoDB;
<사용자 게시물>
CREATE TABLE tunnel.posts(
id INT NOT NULL AUTO_INCREMENT,
userid VARCHAR(30) NOT NULL,
post TEXT NOT NULL,
created_at DATETIME NOT NULL DEFAULT now(),
status TINYINT NOT NULL,
PRIMARY KEY(id),
INDEX userid_idx (userid ASC),
CONSTRAINT commenter FOREIGN KEY (userid) REFERENCES tunnel.users (name)
ON DELETE CASCADE
ON UPDATE CASCADE)
COMMENT = 'post information'
DEFAULT CHARACTER SET = utf8
ENGINE = InnoDB;
<후 처리>
ALTER TABLE tunnel.posts MODIFY post TEXT CHARACTER SET utf8mb4;
:게시물에 이모지 사용가능하게 칼럼 수정.
<댓글>
CREATE TABLE tunnel.comments(
id INT NOT NULL AUTO_INCREMENT,
postid INT NOT NULL,
userid VARCHAR(30) NOT NULL,
created_at DATETIME NOT NULL DEFAULT now(),
comment TEXT NOT NULL,
PRIMARY KEY(id),
INDEX postid_idx (postid ASC),
CONSTRAINT post_id FOREIGN KEY (postid) REFERENCES tunnel.posts (id)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT user_id FOREIGN KEY (userid) REFERENCES tunnel.users (name)
ON UPDATE CASCADE
)
COMMENT = 'post information'
DEFAULT CHARACTER SET = utf8
ENGINE = InnoDB;
<후 처리>
ALTER TABLE tunnel.comments MODIFY comment TEXT CHARACTER SET utf8mb4;
: 댓글에 이모지 사용가능하게 칼럼 수정.
<명령어>
show databases;
use tunnel;
show tables;
DESC tunnel.users ; #유저테이블 자세히 보기
DROP TABLE tunnel.users; #유저테이블 지우기
\ No newline at end of file
{
"development": {
"username": "root",
"password": "tunnel",
"database": "tunnel",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": "tunnel",
"database": "tunnel",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
//mysql사용을 위한 sequelize 세팅 파일
const Sequelize = require('sequelize');
//table(모델)과 연결
const User = require("./user.js");
const env = process.env.NODE_ENV || 'development'; //개발버전
const config = require('../config/config.json')[env];
const db = {};
const sequelize = new Sequelize(config.database, config.username, config.password, config);
db.sequelize = sequelize;
db.User = User;
User.init(sequelize);
User.associate(db);
module.exports = db;
const Sequelize = require('sequelize');
module.exports = class User extends Sequelize.Model {
static init(sequelize) {
return super.init({
name:{
type: Sequelize.STRING(30),
allowNull: false,
unique:true,
},
pw:{
type: Sequelize.STRING(30),
allowNull: false,
},
personality:{
type: Sequelize.CHAR(4),
allowNull: false,
},
status:{
type: Sequelize.BOOLEAN,
allowNull: false,
},
},{
sequelize,
timestamps:false,
underscored:false,
modelName: 'User',
tableName:'users',
paranoid:false,
charset:'utf8',
collate:'utf8_general_ci',
});
}
static associate(db) {}
};
\ No newline at end of file
This diff is collapsed. Click to expand it.
......@@ -9,7 +9,10 @@
"dotenv": "^10.0.0",
"express": "^4.17.1",
"express-session": "^1.17.2",
"morgan": "^1.10.0"
"morgan": "^1.10.0",
"mysql2": "^2.3.3",
"sequelize": "^6.12.0-beta.1",
"sequelize-cli": "^6.3.0"
},
"devDependencies": {
"nodemon": "^2.0.15"
......
......@@ -2,11 +2,21 @@ const express = require("express");
const bodyParser = require("body-parser");
const router = express.Router();
/////////////
const {User}=require('../models');
//////////
router.get('/',(req,res)=>{
res.send('회원가입 페이지');
});
router.post('/',(req,res)=>{
User.create({
name: '고병후',
pw:'1234',
personality:'infj',
status:0
})
console.log(req.body);
return res.json({a: "hi"});
});
......
// 사용 모듈 import
const express = require("express");
const path = require("path");
const morgan = require("morgan");
......@@ -6,6 +7,8 @@ const session = require("express-session");
const dotenv = require("dotenv");
const bodyParser = require("body-parser");
const {sequelize}=require('./models/index.js');
dotenv.config();
const indexRouter = require('./routes/index.js');
const loginRouter = require('./routes/login.js');
......@@ -15,6 +18,15 @@ const app = express();
app.set('port', process.env.PORT || 3001);
const port = app.get('port');
//DB연결
sequelize.sync({force: false})
.then(()=>{
console.log("DB연결 완료")
})
.catch((err)=>{
console.log(err);
});
//미들웨어 설정
app.use(morgan('dev'));
app.use(express.json()); //json형식으로 데이터 전달
......@@ -33,10 +45,6 @@ app.use(session({
//라우팅
//app.use('/',indexRouter);
//app.use('/login',loginRouter);
app.use('/api/register',registerRouter); // 회원가입 페이지
app.use('/api/login',loginRouter); //로그인 페이지
......@@ -53,176 +61,3 @@ app.use((req,res,next)=>{
app.listen(port, ()=>{
console.log(port,"번 포트로 대기중");
});
\ No newline at end of file
//라우팅
/*
//루트페이지
app.get('/', (req,res)=>{
res.sendFile(path.join(__dirname, '/fe/index.html'));
});
//로그인페이지
app.get('/login', (req,res)=>{
res.send("로그인페이지");
});
app.get('/register', (req,res)=>{
res.send("회원가입 페이지");
});
*/
/* 물어볼 부분
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
*/
/*
var users = new Array();
users[0] = {
"userId" : 1,
"name" : "Oh",
"password" : "abc",
"isAdmin" : true
}
users[1] = {
"userId" : 1,
"name" : "Jung",
"password" : "abc",
"isAdmin" : true
}
users[2] = {
"userId" : 2,
"name" : "Go",
"password" : "abc",
"isAdmin" : true
}
app.put('/login', function (req, res) {
var count = 0;
var Found = false;
while(count < users.length) {
if (req.body.userId == users[count].userId
&& req.body.password == users[count].password) {
req.session.userId = users[count].userId;
req.session.isAdmin = users[count].isAdmin;
Found = true;
break;
}
else {
count++;
}
}
if(Found) {
res.send("Login");
}
else {
res.send("Failed");
}
});
app.put('/logout', function (req, res) {
if (req.session.userId == req.body.userId) {
req.session.userId = null;
req.session.isAdmin = false;
res.send("LogOut");
}
else {
res.send("Failed");
}
});
var auth = function (req, res, next) {
if (req.session.userId != null
&& req.session.isAdmin == true)
next();
else
res.send("Error");
};
app.get('/users/:userId', auth,function (req, res) {
var inputId = req.params.userId;
var count = 0;
var Found = false;
while(count < users.length) {
if(inputId == users[count].userId){
Found = true;
res.send(users[count]);
break;
}
else {
count++;
}
}
if (!Found) {
res.send("Not Found");
}
});
app.put('/users',auth,function(req, res){
var inputId = req.body.userId;
var count = 0;
var Found = false;
while (count < users.length) {
if (inputId == users[count].userId) {
Found = true;
users[count] = req.body;
res.send(users[count]);
break;
}
else {
count++;
}
}
if(!Found) {
res.send("Not Found");
}
});
app.post('/users',auth,function(req, res){
var inputData = {
"userId" : req.body.userId,
"name" : req.body.name,
"password" : req.body.password,
"isAdmin" : req.body.isAdmin
}
users.push(inputData);
res.send(inputData);
});
app.delete('/users/:userId',auth,function(req, res){
var inputId = req.params.userId;
var count = 0;
var Found = false;
var removed;
while (count < users.length) {
if (inputId == users[count].userId) {
Found = true;
removed = users.splice(count,1);
console.log(users.length);
res.send(removed);
break;
}
else {
count++;
}
}
if (!Found) {
res.send("Not Found");
}
});
*/
//var server = app.listen(80);
\ No newline at end of file
......