이승윤

Merge branch 'build/node-server' into 'develop'

Build/node server



See merge request !3
node_modules
package-lock.json
\ No newline at end of file
<!DOCTYPE html>
<html>
<body>
<div id="player0"></div>
<div id="player1"></div>
<div id="player2"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var players = [];
players.push('player0');
players.push('player1');
players.push('player2');
var videoIds = [];
videoIds.push('037o6vxm0es');
videoIds.push('kR77WlHRZrs');
videoIds.push('R6IT_f0XPT8');
function onYouTubeIframeAPIReady()
{
for(var i = 0; i < videoIds.length; i++)
{
player = new YT.Player(players[i], {
height: '360',
width: '640',
videoId: videoIds[i],
events: {
// 'onReady': onPlayerReady,
// 'onStateChange': onPlayerStateChange
}
});
}
}
// function onPlayerReady(event) {
// }
// function onPlayerStateChange(event) {
// }
// function stopVideo() {
// }
</script>
</body>
</html>
\ No newline at end of file
나만의 요리 레시피 모음 만들기
이 프로젝트는 youtube를 사용하여 해당 유튜브 채널의 정보 및 동영상을 나의 리스트로 볼 수 있도록 하기위해 만들어질 예정입니다.
var express = require('express');
var app = express();
var port = 3000;
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
//auto-increment를 위한 패키지
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
//passport 로그인 관련
var passport = require('passport');
var session = require('express-session');
var db = mongoose.connection;
db.on('error', console.error);
db.once('open', function () {
console.log('mongo db Connection');
});
var connect = mongoose.connect('mongodb://127.0.0.1:27017/cookBook', {
useMongoClient: true,
});
//admin module get
var admin = require('./routes/admin');
var accounts = require('./routes/accounts');
var auth = require('./routes/auth');
var connectMongo = require('connect-mongo');
var Search = require('./routes/Search');
var MongoStore = connectMongo(session);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/uploads', express.static('uploads'));
var sessionMiddleWare = session({
secret: 'fastcampus',
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 2000 * 60 * 60, //지속시간 2시간
},
store: new MongoStore({
mongooseConnection: mongoose.connection,
ttl: 14 * 24 * 60 * 60,
}),
});
app.use(sessionMiddleWare);
//passport 적용
app.use(passport.initialize());
app.use(passport.session());
//플래시 메시지 관련
app.use(flash());
app.use(function (req, res, next) {
app.locals.isLogin = req.isAuthenticated();
//app.locals.urlparameter = req.url; //현재 url 정보를 보내고 싶으면 이와같이 셋팅
//app.locals.userData = req.user; //사용 정보를 보내고 싶으면 이와같이 셋팅
next();
});
//routes add
app.use('/', Search);
app.use('/admin', admin);
app.use('/accounts', accounts);
app.use('/auth', auth);
var server = app.listen(port, function () {
console.log('Express listening on port', port);
});
var listen = require('socket.io');
var io = listen(server);
//socket io passport 접근하기 위한 미들웨어 적용
io.use(function (socket, next) {
sessionMiddleWare(socket.request, socket.request.res, next);
});
require('./libs/socketConnection')(io);
module.exports = function(req, res, next) {
if (!req.isAuthenticated()){
res.redirect('/accounts/login');
}else{
return next();
}
};
\ No newline at end of file
var crypto = require('crypto');
var mysalt = "fastcampus";
module.exports = function(password){
return crypto.createHash('sha512').update( password + mysalt).digest('base64');
};
\ No newline at end of file
module.exports = function(){
Array.prototype.removeByValue = function (search) {
var index = this.indexOf(search);
if (index !== -1) {
this.splice(index, 1);
}
};
};
\ No newline at end of file
require('./removeByValue')();
var userList = []; //사용자 리스트를 저장할곳
module.exports = function(io) {
io.on('connection', function(socket){
var session = socket.request.session.passport;
var user = (typeof session !== 'undefined') ? ( session.user ) : "";
// userList 필드에 사용자 명이 존재 하지 않으면 삽입
if(userList.indexOf(user.displayname) === -1){
userList.push(user.displayname);
}
io.emit('join', userList);
//사용자 명과 메시지를 같이 반환한다.
socket.on('client message', function(data){
io.emit('server message', { message : data.message , displayname : user.displayname });
});
socket.on('disconnect', function(){
userList.removeByValue(user.displayname);
io.emit('leave', userList);
});
});
};
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<title>Hello OSS!</title>
</head>
<body>
<header>
<center>
<h1>나의 요리비급서 from YouTube</h1>
</center>
<hr align="center" width=50%>
</hr>
</header>
</body>
</html>
\ No newline at end of file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//생성될 필드명을 정한다.
var ProductsSchema = new Schema({
name: {
//제품명
type: String,
required: [true, '제목은 입력해주세요'],
},
thumbnail: String, //이미지 파일명
price: Number, //가격
description: String, //설명
created_at: {
//작성일
type: Date,
default: Date.now(),
},
username: String, //작성자추가
});
ProductsSchema.virtual('getDate').get(function () {
var date = new Date(this.created_at);
return {
year: date.getFullYear(),
month: date.getMonth() + 1,
day: date.getDate(),
};
});
// 1씩 증가하는 primary Key를 만든다
// model : 생성할 document 이름
// field : primary key , startAt : 1부터 시작
module.exports = mongoose.model('products', ProductsSchema);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: {
type: String,
required: [true, '아이디는 필수입니다.'],
},
password: {
type: String,
required: [true, '패스워드는 필수입니다.'],
},
displayname: String,
created_at: {
type: Date,
default: Date.now(),
},
});
module.exports = mongoose.model('user', UserSchema);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var VideoSchema = new Schema({
name: String,
title: String,
videoId: String,
description: String, //설명
url: String,
});
module.exports = mongoose.model('videos', VideoSchema);
{
"name": "node",
"version": "1.0.0",
"description": "my-cookbook-project",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon ./app.js"
},
"dependencies": {
"body-parser": "^1.18.2",
"connect-flash": "^0.1.1",
"connect-mongo": "^2.0.0",
"cookie-parser": "^1.4.3",
"csurf": "^1.9.0",
"ejs": "^2.5.7",
"express": "^4.15.4",
"express-session": "^1.15.5",
"mongodb": "^2.2.36",
"mongoose": "^4.13.21",
"morgan": "^1.8.2",
"multer": "^1.3.0",
"passport": "^0.4.0",
"passport-facebook": "^2.1.1",
"passport-local": "^1.0.0",
"path": "^0.12.7",
"socket.io": "^2.0.3",
"youtube-node": "^1.3.3"
}
}
var Youtube = require('youtube-node');
var youtube = new Youtube();
var express = require('express');
var router = express.Router();
var word = '백종원 레시피'; // 검색어 지정
var limit = 10; // 출력 갯수
var video = [];
var test = 'test';
var count = 0;
youtube.setKey('AIzaSyAsKr_oWGZIBbL5tLdIl98Lf9Pzqj8jX4o'); // API 키 입력
youtube.addParam('order', 'rating'); // 평점 순으로 정렬
youtube.addParam('type', 'video'); // 타입 지정
youtube.addParam('videoLicense', 'creativeCommon'); // 크리에이티브 커먼즈 아이템만 불러옴
youtube.search(word, limit, function (err, result) {
// 검색 실행
if (err) {
console.log(err);
} // 에러일 경우 에러공지하고 빠져나감
//console.log(JSON.stringify(result, null, 2)); // 받아온 전체 리스트 출력
var items = result['items']; // 결과 중 items 항목만 가져옴
for (var i in items) {
var it = items[i];
for (var j in it) {
if (it[j]['title'] != null) {
var title = it[j]['title'];
}
if (it[j]['videoId'] != null) {
var video_id = it[j]['videoId'];
}
var urls = 'https://www.youtube.com/watch?v=' + video_id;
}
var item = {
id: count,
title: title,
video_id: video_id,
urls: urls,
};
count++;
video.push(item);
}
});
router.get('/', function (req, res) {
res.render(
'home',
{ videos: video } // DB에서 받은 videos를 videos변수명으로 내보냄
);
});
module.exports = router;
var express = require('express');
var router = express.Router();
var UserModel = require('../models/UserModel');
var passwordHash = require('../libs/passwordHash');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
passport.serializeUser(function (user, done) {
console.log('serializeUser');
done(null, user);
});
passport.deserializeUser(function (user, done) {
var result = user;
result.password = "";
console.log('deserializeUser');
done(null, result);
});
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField : 'password',
passReqToCallback : true
},
function (req, username, password, done) {
UserModel.findOne({ username : username , password : passwordHash(password) }, function (err,user) {
if (!user){
return done(null, false, { message: '아이디 또는 비밀번호 오류 입니다.' });
}else{
return done(null, user );
}
});
}
));
router.get('/', function(req, res){
res.send('account app');
});
router.get('/join', function(req, res){
res.render('accounts/join');
});
router.post('/join', function(req, res){
var User = new UserModel({
username : req.body.username,
password : passwordHash(req.body.password),
displayname : req.body.displayname
});
User.save(function(err){
res.send('<script>alert("회원가입 성공");location.href="/accounts/login";</script>');
});
});
router.get('/login', function(req, res){
res.render('accounts/login', { flashMessage : req.flash().error });
});
router.post('/login' ,
passport.authenticate('local', {
failureRedirect: '/accounts/login',
failureFlash: true
}),
function(req, res){
res.send('<script>alert("로그인 성공");location.href="/";</script>');
}
);
router.get('/success', function(req, res){
res.send(req.user);
});
router.get('/logout', function(req, res){
req.logout();
res.redirect('/accounts/login');
});
module.exports = router;
\ No newline at end of file
var express = require('express');
var router = express.Router();
var ProductsModel = require('../models/ProductsModel');
var CommentsModel = require('../models/VideoModels');
var csrf = require('csurf');
var csrfProtection = csrf({ cookie: true });
var loginRequired = require('../libs/loginRequired');
var path = require('path');
var uploadDir = path.join(__dirname, '../uploads'); // 루트의 uploads위치에 저장한다.
var fs = require('fs');
//multer 셋팅
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
//이미지가 저장되는 도착지 지정
callback(null, uploadDir);
},
filename: function (req, file, callback) {
// products-날짜.jpg(png) 저장
callback(
null,
'products-' + Date.now() + '.' + file.mimetype.split('/')[1]
);
},
});
var upload = multer({ storage: storage });
router.get('/', function (req, res) {
res.send('admin main page');
});
router.get('/products', function (req, res) {
ProductsModel.find(function (err, products) {
res.render(
'admin/products',
{ products: products }
//ProductModel의 products를 받아서
//admin/products로 response를 보낸다.
);
});
});
router.get(
'/products/write',
loginRequired,
csrfProtection,
function (req, res) {
//edit에서도 같은 form을 사용하므로 빈 변수( product )를 넣어서 에러를 피해준다
res.render('admin/form', { product: '', csrfToken: req.csrfToken() });
}
);
router.post(
'/products/write',
upload.single('thumbnail'),
loginRequired,
csrfProtection,
function (req, res) {
var product = new ProductsModel({
name: req.body.name,
thumbnail: req.file ? req.file.filename : '',
price: req.body.price,
description: req.body.description,
username: req.user.username,
});
//이 아래는 수정되지 않았음
var validationError = product.validateSync();
if (validationError) {
res.send(validationError);
} else {
product.save(function (err) {
res.redirect('/admin/products');
});
}
//이 위는 수정되지 않았음
}
);
router.get('/products/detail/:id', function (req, res) {
//url 에서 변수 값을 받아올떈 req.params.id 로 받아온다
ProductsModel.findOne({ id: req.params.id }, function (err, product) {
//제품정보를 받고 그안에서 댓글을 받아온다.
CommentsModel.find({ product_id: req.params.id }, function (err, comments) {
res.render('admin/productsDetail', {
product: product,
comments: comments,
});
});
});
});
router.get(
'/products/edit/:id',
loginRequired,
csrfProtection,
function (req, res) {
//기존에 폼에 value안에 값을 셋팅하기 위해 만든다.
ProductsModel.findOne({ id: req.params.id }, function (err, product) {
res.render('admin/form', {
product: product,
csrfToken: req.csrfToken(),
});
});
}
);
router.post(
'/products/edit/:id',
loginRequired,
upload.single('thumbnail'),
csrfProtection,
function (req, res) {
//그전에 지정되 있는 파일명을 받아온다
ProductsModel.findOne({ id: req.params.id }, function (err, product) {
//아래의 코드만 추가되면 된다.
if (req.file && product.thumbnail) {
//요청중에 파일이 존재 할시 이전이미지 지운다.
fs.unlinkSync(uploadDir + '/' + product.thumbnail);
}
//위의 코드만 추가되면 된다.
//넣을 변수 값을 셋팅한다
var query = {
name: req.body.name,
thumbnail: req.file ? req.file.filename : product.thumbnail,
price: req.body.price,
description: req.body.description,
};
ProductsModel.update(
{ id: req.params.id },
{ $set: query },
function (err) {
res.redirect('/admin/products/detail/' + req.params.id);
}
);
});
}
);
router.get('/products/delete/:id', function (req, res) {
ProductsModel.remove({ id: req.params.id }, function (err) {
res.redirect('/admin/products');
});
});
router.post('/products/ajax_comment/insert', function (req, res) {
var comment = new CommentsModel({
content: req.body.content,
product_id: parseInt(req.body.product_id),
});
comment.save(function (err, comment) {
res.json({
id: comment.id,
content: comment.content,
message: 'success',
});
});
});
router.post('/products/ajax_comment/delete', function (req, res) {
CommentsModel.remove({ id: req.body.comment_id }, function (err) {
res.json({ message: 'success' });
});
});
module.exports = router;
var express = require('express');
var router = express.Router();
var UserModel = require('../models/UserModel');
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
});
passport.use(new FacebookStrategy({
// https://developers.facebook.com에서 appId 및 scretID 발급
clientID: "863352300499259", //입력하세요
clientSecret: "36867723fbdd49dac987f9a061e2206a", //입력하세요.
callbackURL: "http://localhost:3000/auth/facebook/callback",
profileFields: ['id', 'displayName', 'photos', 'email'] //받고 싶은 필드 나열
},
function(accessToken, refreshToken, profile, done) {
//아래 하나씩 찍어보면서 데이터를 참고해주세요.
//console.log(profile);
//console.log(profile.displayName);
//console.log(profile.emails[0].value);
//console.log(profile._raw);
//console.log(profile._json);
UserModel.findOne({ username : "fb_" + profile.id }, function(err, user){
if(!user){ //없으면 회원가입 후 로그인 성공페이지 이동
var regData = { //DB에 등록 및 세션에 등록될 데이터
username : "fb_" + profile.id,
password : "facebook_login",
displayname : profile.displayName
};
var User = new UserModel(regData);
User.save(function(err){ //DB저장
done(null,regData); //세션 등록
});
}else{ //있으면 DB에서 가져와서 세션등록
done(null,user);
}
});
}
));
// http://localhost:3000/auth/facebook 접근시 facebook으로 넘길 url 작성해줌
router.get('/facebook', passport.authenticate('facebook', { scope: 'email'}) );
//인증후 페이스북에서 이 주소로 리턴해줌. 상단에 적은 callbackURL과 일치
router.get('/facebook/callback',
passport.authenticate('facebook',
{
successRedirect: '/',
failureRedirect: '/auth/facebook/fail'
}
)
);
//로그인 성공시 이동할 주소
router.get('/facebook/success', function(req,res){
res.send(req.user);
});
router.get('/facebook/fail', function(req,res){
res.send('facebook login fail');
});
module.exports = router;
\ No newline at end of file
<% include ../includes/header.ejs %>
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">회원가입</h3>
</div>
<div class="panel-body">
<form role="form" action="" id="join_form" method="post">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="ID" name="username" type="text" autofocus="" required="">
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="" required="">
</div>
<div class="form-group">
<input class="form-control" placeholder="Password 확인" name="password2" type="password" value="" required="">
</div>
<div class="form-group">
<input class="form-control" placeholder="이름" name="displayname" type="text" value="" required="">
</div>
<!-- Change this to a button or input when using this as a form -->
<input type="submit" class="btn btn-lg btn-success btn-block" value="가입하기">
<div style="margin-top: 10px">
<a href="/auth/facebook" class="btn btn-lg btn-primary btn-block">
<i class="fa fa-facebook" aria-hidden="true"></i> 페이스북 회원가입
</a>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
(function(){
$(document).ready(function() {
$('#join_form').submit(function(){
var $usernameInput = $('#join_form input[name=username]');
var $passwordInput = $('#join_form input[name=password]');
var $passwordInput2 = $('#join_form input[name=password2]');
var $displayname = $('#join_form input[name=displayname]');
if(!$usernameInput.val()){
alert("아이디를 입력해주세요.");
$usernameInput.focus();
return false;
}
if(!$passwordInput.val()){
alert("패스워드를 입력해주세요.");
$passwordInput.focus();
return false;
}
if(!$passwordInput2.val()){
alert("확인 패스워드를 입력해주세요.");
$passwordInput2.focus();
return false;
}
if(!$displayname.val()){
alert("이름을 입력해주세요.");
$displayname.focus();
return false;
}
if($passwordInput.val() !== $passwordInput2.val()){
alert("패스워드와 확인용패스워드를 똑같이 입력해주세요.");
return false;
}
return true;
});
});
})();
</script>
<% include ../includes/footer.ejs %>
\ No newline at end of file
<% include ../includes/header.ejs %>
<div class="row">
<div class="col-md-4 col-md-offset-4">
<%if(typeof flashMessage !=='undefined') {%>
<div class="alert alert-danger" role="alert"><%=flashMessage%></div>
<%}%>
<div class="login-panel panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">로그인</h3>
</div>
<div class="panel-body">
<form role="form" action="" id="login_form" method="post">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="ID" name="username" type="text" autofocus="" required="">
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="" required="">
</div>
<!-- Change this to a button or input when using this as a form -->
<input type="submit" class="btn btn-lg btn-success btn-block" value="로그인">
<div style="margin-top: 10px">
<a href="/auth/facebook" class="btn btn-lg btn-primary btn-block">
<i class="fa fa-facebook" aria-hidden="true"></i> 페이스북 로그인
</a>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
(function(){
$(document).ready(function() {
$('#login_form').submit(function(){
var $usernameInput = $('#login_form input[name=username]');
var $passwordInput = $('#login_form input[name=password]');
if(!$usernameInput.val()){
alert("아이디를 입력해주세요.");
$usernameInput.focus();
return false;
}
if(!$passwordInput.val()){
alert("패스워드를 입력해주세요.");
$passwordInput.focus();
return false;
}
return true;
});
});
})();
</script>
<% include ../includes/footer.ejs %>
\ No newline at end of file
<% include ../includes/header.ejs %>
<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="_csrf" value="<%=csrfToken%>" />
<table class="table table-bordered">
<tr>
<th>제품명</th>
<td><input type="text" name="name" class="form-control" value="<%=product.name%>"/></td>
</tr>
<tr>
<th>섬네일</th>
<td>
<input type="file" name="thumbnail" />
<% if(product.thumbnail){ %>
<a href="/uploads/<%=product.thumbnail%>" target="_blank">업로드 이미지 보기</a>
<% } %>
</td>
</tr>
<tr>
<th>가격</th>
<td><input type="text" name="price" class="form-control" value="<%=product.price%>"/></td>
</tr>
<tr>
<th>설명</th>
<td><input type="text" name="description" class="form-control" value="<%=product.description%>"/></td>
</tr>
</table>
<button class="btn btn-primary">작성하기</button>
</form>
<% include ../includes/footer.ejs %>
\ No newline at end of file
<% include ../includes/header.ejs %>
<table class="table table-bordered table-hover">
<tr>
<th>제목</th>
<th>작성일</th>
<th>삭제</th>
</tr>
<%products.forEach(function(product){%>
<tr>
<td>
<a href="/admin/products/detail/<%=product.id%>"><%=product.name%></a>
</td>
<td>
<%=product.getDate.year%> -
<%=product.getDate.month%> -
<%=product.getDate.day%>
</td>
<td>
<a href="/admin/products/delete/<%=product.id%>" class="btn btn-danger" onclick="return confirm('삭제하시겠습니까?')">삭제</a>
</td>
</tr>
<% }); %>
</table>
<a href="/admin/products/write" class="btn btn-default">작성하기</a>
<% include ../includes/footer.ejs %>
\ No newline at end of file
<% include ../includes/header.ejs %>
<div class="panel panel-default">
<div class="panel-heading">
<%=product.name%>
</div>
<div class="panel-body">
<div style="padding-bottom: 10px">
작성일 :
<%=product.getDate.year%> -
<%=product.getDate.month%> -
<%=product.getDate.day%>
</div>
<% if(product.thumbnail){%>
<p>
<img src="/uploads/<%=product.thumbnail%>" style="max-width: 100%"/>
</p>
<% } %>
<%=product.description%>
<!-- 댓글영역 -->
<div>
댓글작성하기
<form id="commentForm" action="" method="post">
<input type="hidden" name="product_id" value="<%=product.id%>" />
<textarea class="form-control" name="content"></textarea>
<button class="btn btn-primary" style="margin-top: 10px">댓글작성</button>
</form>
</div>
<!-- 댓글영역 -->
<hr />
<div id="comment_area">
<% comments.forEach(function(comment){ %>
<div>
<%=comment.content%>
( <a class='comment_delete' comment_id='<%=comment.id%>'>삭제</a> )
</div>
<% }); %>
</div>
</div>
</div>
<a href="/admin/products" class="btn btn-default">목록으로</a>
<a href="/admin/products/edit/<%=product.id%>" class="btn btn-primary">수정</a>
<% include ../includes/footer.ejs %>
<script>
(function(){
$(document).ready(function() {
$('#commentForm').submit(function(){
var $contentVal = $(this).children('textarea[name=content]').val();
if($contentVal){
$.ajax({
url: '/admin/products/ajax_comment/insert',
type: 'POST',
data: $(this).serialize(),
})
.done(function(args) {
if(args.message==="success"){
$('#comment_area').append(
'<div>' + args.content +
" ( <a class='comment_delete' comment_id='"+ args.id +"'>삭제</a> ) </div>"
);
$('#commentForm textarea[name=content]').val("");
}
})
.fail(function(args) {
console.log(args);
});
}else{
alert('댓글 내용을 입력해주세요.')
}
return false;
});
});
})();
</script>
<script>
$(document).on('click' , '.comment_delete' , function(){
if(confirm('삭제하시겠습니까?')){ //확인창 예 눌렀을 시만 진행
var $self = $(this);
$.ajax({
url: '/admin/products/ajax_comment/delete',
type: 'POST',
data: { comment_id : $self.attr('comment_id') },
})
.done(function() {
$self.parent().remove();
alert("삭제가 완료되었습니다.");
})
.fail(function(args) {
console.log(args);
});
}
});
</script>
\ No newline at end of file
<% include ./includes/header.ejs %>
<div class="container" id="masonry_container">
<% for (var i in videos) { %>
<div id="<%=videos[i].id%>" vid="<%=videos[i].video_id%>">
</div>
<%};%>
</div>
<style type="text/css">
.masonry-grid img { max-width: 260px; }
</style>
<script src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.1/imagesloaded.pkgd.min.js"></script>
<script type="text/javascript">
var $masonry_container = $('#masonry_container');
$masonry_container.imagesLoaded(function(){
$masonry_container.masonry({
itemSelector : '.masonry-grid',
columnWidth : 270
});
});
</script>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var players = [];
var videoIds = [];
for (var i = 0;i<10;i++) {
players.push(String(i));
videoIds.push($('#'+i).attr('vid'));
}
function onYouTubeIframeAPIReady() {
for (var i = 0; i < videoIds.length; i++) {
player = new YT.Player(players[i], {
height: '360',
width: '640',
videoId: videoIds[i],
events: {
// 'onReady': onPlayerReady,
// 'onStateChange': onPlayerStateChange
}
});
}
}
// function onPlayerReady(event) {
// }
// function onPlayerStateChange(event) {
// }
// function stopVideo() {
// }
</script>
<% include ./includes/footer.ejs %>
\ No newline at end of file
</div>
</body>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>MYCOOK</title>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!--bootstrap js 추가 -->
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="padding-top: 10px;">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<!-- 오른쪽 메뉴바 -->
<button type="button" class="collapsed navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-9" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="/" class="navbar-brand">MyCookBook</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-9">
<ul class="nav navbar-nav">
<li class="active">
<a href="/">Home</a>
</li>
<li><a href="/admin/products">Categori</a></li>
<% if(isLogin){%>
<li><a href="/accounts/logout" onclick="return confirm('로그아웃 하시겠습니까?')">LOGOUT</a></li>
<%}else{%>
<li><a href="/accounts/join">SignUp</a></li>
<li><a href="/accounts/login">LOGIN</a></li>
<%}%>
</ul>
</div>
</div>
</nav>