-
글쓴이글
-
2022년 3월 17일 22:24 #29732
서영석참가자강사님의 상세페이지를 만든 것을 보면서 연습하고 있습니다.
<!doctype html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="/public/main.css">
<title>블루밍 상세페이지</title>
</head>
<body>
<%- include('nav.html') %>
<h4 class="ml-2 my-3 text-center">상품 목록</h4>
<div class="container input-group mb-2">
<input class="form-control" id="search-input">
<button class="input-group-append btn btn-danger" id="search">검색</button>
</div><div class="container">
<ul class="list-group">
<% for (var i=0; i < products.length; i++){ %>
<li class="list-group-item">
<!-- <p>
상품시리얼번호 : <%= products[i].상품시리얼번호 %>
</p> -->
<h4> 상품번호 : <%= products[i]._id %></h4>
<h4> 상품이름 : <%= products[i].상품이름 %></h4>
<p>
판매가격 : <%= products[i].판매가격 %>
</p>
<h3> 상세설명 : <%= products[i].상세설명 %></h3>
<button type="button" onclick="location.href='shop'" class="btn btn-danger">구매</button>
</li>
<% } %>
</ul>
</div><script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$('#search').click(function(){
var 입력한값 = $('#search-input').val()
window.location.replace('/search?value=' + 입력한값)
})
</script><script>
function getData(callbackFunc) {
$.get('shop/:id', function(response) {
callbackFunc(response); // 서버에서 받은 데이터 response를 callbackFunc() 함수에 넘겨줌
});
}getData(function(tableData) {
console.log(tableData); // $.get()의 response 값이 tableData에 전달됨
});
</script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>위 .ejs 파일을 button을 이용하여 화면을 전환해
<!doctype html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="/public/main.css">
<title>블루밍 상세페이지</title>
</head>
<body>
<%- include('nav.html') %><h4>상세페이지</h4>
<h4>상품이름 : <%= data.상품이름 %></h4>
<h4>판매가격 : <%= data.판매가격 %></h4>
<a href="/shop/:id>" class="card-link"></a>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script><!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>상세페이지의 url인 /shop/:id로 버튼에스 링크하면 되나요
아니면 <script>
$('.delete').click(function(e){ delete에서 insert로 바꾸고
var 글번호 = e.target.dataset.id; //내가 누른 버튼에 숨겨진 data-id을 가져와주세요
var 지금누른거 = $(this);
$.ajax({
method : 'DELETE', 이부분을 :/'INSERT',
url : '/delete',
data : { _id : 글번호} :/_id:상품번호로 바꾸면 되는 건가요
}).done(function(결과){
//페이지를 강제로 새로 고침해주세요
//삭제 버튼을 누른 <li> 요소를 제거해주세요/안보이게
console.log('성공했어염')
지금누른거.parent('li').fadeOut();
}).fall(function(xhr, textStatus, errorThrown){
console.log(xhr, textStatus, errorThrown);
});
});
</script>ReferenceError: C:\Users\sys69\Desktop\appfume\views\shop.ejs:17
15| <h4>상세페이지</h4>16|
>> 17| <h4>상품이름 : <%= data.상품이름 %></h4>
18| <h4>판매가격 : <%= data.판매가격 %></h4>
19| <a href="/shop>" class="card-link"></a>
20| <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
data is not defined
at eval ("C:\\Users\\sys69\\Desktop\\appfume\\views\\shop.ejs":15:26)
at shop (C:\Users\sys69\Desktop\appfume\node_modules\ejs\lib\ejs.js:692:17)
at tryHandleCache (C:\Users\sys69\Desktop\appfume\node_modules\ejs\lib\ejs.js:272:36)
at View.exports.renderFile [as engine] (C:\Users\sys69\Desktop\appfume\node_modules\ejs\lib\ejs.js:489:10)
at View.render (C:\Users\sys69\Desktop\appfume\node_modules\express\lib\view.js:135:8)
at tryRender (C:\Users\sys69\Desktop\appfume\node_modules\express\lib\application.js:640:10)
at Function.render (C:\Users\sys69\Desktop\appfume\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (C:\Users\sys69\Desktop\appfume\node_modules\express\lib\response.js:1017:7)
at C:\Users\sys69\Desktop\appfume\app.js:47:4
at Layer.handle [as handle_request] (C:\Users\sys69\Desktop\appfume\node_modules\express\lib\router\layer.js:95:5)에러는 입니다.
질문을 올리게 되었습니다.
2022년 3월 18일 09:53 #29749
codingapple키 마스터상세페이지를 서버에서 보내줄 때 data라는 변수를 ejs파일에 안보냈다는 에러같군요 보내봅시다
<a href="/shop/:id> 이것도 이상한데 따옴표끝나는게 없고 :id자리에 ejs 문법으로 변수같은걸 넣어야할듯요
<a href="/shop/<%= data.상품_id이런거 %> ">
이래야 잘 이동하지않을까요 근데 서버에 app.get('/shop/:id' 부분을 어떻게 만들었는지 확인하고 기입해야합니다
2022년 3월 18일 11:16 #29755
서영석참가자const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(express.urlencoded({extended: true}));
const MongoClient = require('mongodb').MongoClient;
const MongoStore = require('connect-mongo');
const methodOverride = require('method-override');
const { redirect } = require('express/lib/response');
app.use(methodOverride('_method'))
app.set('view engine', 'ejs');app.use('/public', express.static('public'));
var db;
MongoClient.connect('mongodb+srv://scott:scott@cluster0.eeagm.mongodb.net/perfumeapp?retryWrites=true&w=majority', function(에러, client){
if(에러) return console.log(에러)
db = client.db('perfumeapp'); //database 이름 perfumeappconsole.log('저장완료');
});app.listen(4626, function(){
console.log('listening on 4626')
});app.get('/sub', function(요청, 응답){
응답.render('sub.ejs')
});app.get('/', function(요청, 응답){
응답.render('index.ejs')
});app.get('/complete', function(요청, 응답){
응답.render('complete.ejs')
});app.get('/logout', function(요청, 응답){
응답.render('logout.ejs')
});app.get('/shop', function(요청, 응답){
응답.render('shop.ejs')
});app.get('/order', function(요청, 응답){
응답.render('order.ejs')
});app.get('/buy', function(요청, 응답){
응답.render('buy.ejs')
});app.get('/record', function(요청, 응답){
응답.render('record.ejs')
});// app.get('/register', function(요청, 응답){
// 응답.render('join.ejs')
// });app.get('/order',function(요청,응답){
응답.render('order.ejs')
});app.post('/buy', function(요청, 응답){
응답.send('전송완료');
db.collection('incart').insertOne({상품이름 : 요청.body.productname, 판매가격 : 요청.body.productprice},function(){
응답.redirect('/shop')
})
})app.post('/add', function(요청, 응답){
응답.send('전송완료');
db.collection('productcounter').findOne({name : '상품갯수'}, function(에러, 결과){
console.log(결과.AllProduct)
var 총상품갯수 = 결과.AllProduct;db.collection('product').insertOne( { _id : 총상품갯수 + 1,상품시리얼번호: 요청.body.productnum, 상품이름 : 요청.body.productname,상품수량 : 요청.body.productcount, 판매가격 : 요청.body.productprice, 상세설명: 요청.body.productdetail } , function(){
console.log('저장완료');
db.collection('productcounter').updateOne({name:'상품갯수'},{ $inc :{AllProduct:1}},function(에러,결과){
if(에러){return console.log(에러)}
})
});
});
});// app.post('/plus', function(요청, 응답){
// 응답.send('전송완료');
// db.collection('productcount').findOne({name: '상품갯수'}, function(에러, 결과){
// // console.log(결과.TotalProduct)
// var 상품갯수 = 결과.totalProduct;
// var 저장할거 = {_id : 상품갯수 + 1, 상품이름 : 요청.body.productname, 상품가격 : 요청.body.productprice, 상세설명 : 요청.body.productdetail}
// db.collection('product').insertOne( { _id : 상품갯수 + 1, 상품이름 : 요청.body.pfname, 상품가격 : 요청.body.pfsprice, 상세설명 : 요청.body.pfdetail} , function(){
// console.log('저장완료');
// db.collection('productcount').updateOne({name : '상품총갯수'}, {$inc : {totalProduct : 0}}, function(에러, 결과){
// if(에러){return console.log(에러)}
// 응답.send('전송완료');
// });
// });
// });
// });app.get('/list', function(요청, 응답){
db.collection('product').find().toArray(function(에러, 결과){
console.log(결과);
응답.render('list.ejs',{products : 결과});
});
});app.get('/shop/:id', function(요청, 응답){
db.collection('product').findOne({_id : parseInt(요청.params.id)}, function(에러,결과){
console.log(결과);
응답.render('shop.ejs',{ data : 결과})
})
});// app.post('/plus', function(요청, 응답){
// 응답.send('전송완료');
// db.collection('productcount').findOne({name: '상품갯수'}, function(에러, 결과){
// console.log(결과.totalProduct)
// var 상품갯수 = 결과.totalProduct;// db.collection('product').insertOne( { _id : (상품갯수) + 1, 상품이름 : 요청.body.pfname, 판매가격 : 요청.body.pfsprice, 상세설명 : 요청.body.pfdetail} , function(){
// console.log('저장완료');
// db.collection('productcount').updateOne({name : '상품갯수'}, {$inc : {totalProduct : 1}}, function(에러, 결과){
// if(에러){return console.log(에러)}
// 응답.send('전송완료');
// });
// });
// });
// });const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const session = require('express-session');
const res = require('express/lib/response');app.use(session({secret : '비밀코드', resave : true, saveUninitialized: false}));
app.use(passport.initialize());
app.use(passport.session());app.get('/login', function(요청, 응답){
응답.render('login.ejs')
});app.post('/logout',function(요청, 응답){
req.logout();
res.redirect('/');
});app.post('/login', passport.authenticate('local', {
failureRedirect : '/fall'
}), function(요청, 응답){
응답.redirect('/sub')
});app.get('/list', function(요청, 응답){
db.collection('product').find().toArray(function(에러, 결과){
console.log(결과);
응답.render('list.ejs',{products : 결과});
})
})app.get('/shop/:id', function(요청, 응답){
db.collection('product').findOne({_id : parseInt(요청.params.id)}, function(에러,결과){
console.log(결과);
응답.render('shop.ejs',{data : 결과})
})
});// app.get('/record', 로그인했니, function(요청,응답){
// console.log(요청.user);
// 응답.render('record.ejs',{사용자: 요청.user})
// })// function 로그인했니(요청, 응답, next) {
// if (요청.user) {
// next()
// }
// else {
// 응답.send('로그인안하셨는데요?')
// }
// }app.get('/mypage', 로그인했니, function(요청,응답){
console.log(요청.user);
응답.render('mypage.ejs',{사용자: 요청.user})
})function 로그인했니(요청, 응답, next) {
if (요청.user) {
next()
}
else {
응답.send('로그인안하셨는데요?')
}
}
passport.use(new LocalStrategy({
usernameField: 'uid',
passwordField: 'pw1',
session: true,
passReqToCallback: false,
}, function (입력한아이디, 입력한비번, done) {
//console.log(입력한아이디, 입력한비번);
db.collection('user').findOne({ uid: 입력한아이디 }, function (에러, 결과) {
if (에러) return done(에러)
if (!결과) return done(null, false, { message: '존재하지않는 아이디요' })
if (입력한비번 == 결과.pw1) {
return done(null, 결과)
} else {
return done(null, false, { message: '비번틀렸어요' })
}
})
}));passport.serializeUser(function (user, done) {
done(null, user.uid)
});
passport.deserializeUser(function (아이디, done) {
db.collection('user').findOne({uid : 아이디}, function(에러, 결과){
done(null, 결과)
})
});app.post('/register', function (요청, 응답) {
db.collection('user').insertOne({ uid: 요청.body.uid, pw1: 요청.body.pw1, pw2: 요청.body.pw2, 이름: 요청.body.name, 성별: 요청.body.gender, 휴대폰번호:요청.body.ph }, function (에러, 결과) {
응답.redirect('/')
});
});app.get('/shop/:id', function(요청, 응답){
db.collection('product').findOne({_id : parseInt(요청.params.id)}, function(에러,결과){
console.log(결과);
응답.render('shop.ejs',{ data : 결과})
})
});// app.post('/record', function(요청, 응답){
// db.collection('product')
// });// app.post('/plus', function(요청, 응답){
// 응답.send('전송완료');
// db.collection('productcount').findOne({name: '상품갯수'}, function(에러, 결과){
// console.log(결과.totalProduct)
// var 상품갯수 = 결과.totalProduct;// db.collection('product').insertOne( { _id : (상품갯수) + 1, 상품이름 : 요청.body.pfname, 상품가격 : 요청.body.pfsprice, 상세설명 : 요청.body.pfdetail} , function(){
// console.log('저장완료');
// db.collection('productcount').updateOne({name : '상품갯수'}, {$inc : {totalProduct : 1}}, function(에러, 결과){
// if(에러){return console.log(에러)}
// 응답.send('전송완료');
// });
// });
// });app.js에서
app.get('/shop/:id', function(요청, 응답){
db.collection('product').findOne({_id : parseInt(요청.params.id)}, function(에러,결과){
console.log(결과);
응답.render('shop.ejs',{ data : 결과})
})
});이렇게해서 하는 것이 아닌가요?
2022년 3월 18일 23:45 #29814
서영석참가자주소에 shop/1 했을때 상품이 나옵니다.
를 shop/:id 로 하니 data is not define이라고 나옵니다.
ReferenceError: C:\Users\sys69\Desktop\appfume\views\shop.ejs:17
15| <h4>상세페이지</h4>16|
>> 17| <h4>상품이름 : <%= data.상품이름 %></h4>
18| <h4>판매가격 : <%= data.판매가격 %></h4>
19| <a href="/shop/<%= data.상품번호_id%> ">
20| <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
data is not defined
at eval ("C:\\Users\\sys69\\Desktop\\appfume\\views\\shop.ejs":15:26)
at shop (C:\Users\sys69\Desktop\appfume\node_modules\ejs\lib\ejs.js:692:17)
at tryHandleCache (C:\Users\sys69\Desktop\appfume\node_modules\ejs\lib\ejs.js:272:36)
at View.exports.renderFile [as engine] (C:\Users\sys69\Desktop\appfume\node_modules\ejs\lib\ejs.js:489:10)
at View.render (C:\Users\sys69\Desktop\appfume\node_modules\express\lib\view.js:135:8)
at tryRender (C:\Users\sys69\Desktop\appfume\node_modules\express\lib\application.js:640:10)
at Function.render (C:\Users\sys69\Desktop\appfume\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (C:\Users\sys69\Desktop\appfume\node_modules\express\lib\response.js:1017:7)
at C:\Users\sys69\Desktop\appfume\app.js:47:4
at Layer.handle [as handle_request] (C:\Users\sys69\Desktop\appfume\node_modules\express\lib\router\layer.js:95:5)오류로 나옵니다
주소창으로 직접 치면 나오고 링크로는 나오지 않습니다.
2022년 3월 19일 10:20 #29835
codingapple키 마스터그럼 링크도 <a href="/shop/상품아이디"> 로 만들어야합니다
:id는 서버에서만 쓰는 문법입니다
<a href="/shop/<%= data.상품_id같은거 %> "> 이래야할듯요
-
글쓴이글
- 답변은 로그인 후 가능합니다.