• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Node.js, Express 게시판 수정기능 오류 문의입니다.

수정기능 오류 문의입니다.

  • 이 주제에는 9개 답변, 2명 참여가 있으며 jay3 년 전에 전에 마지막으로 업데이트했습니다.
10 글 보임 - 1 에서 10 까지 (총 10 중에서)
  • 글쓴이
  • #39171

    jay
    참가자
    안녕하세요.
    http://localhost:8080/edit/1
    _id 1을 수정하려했을 때, 에러가 나옵니다.
    
    '_id' 의 '1' 은 한번 잘 가져오는데요.
    'null'을 한번 더 가져오면서 에러가 나오네요.
    db 내용 수정도 안되어있습니다. 브라우저의 컨설창에서는
    GET http://localhost:8080/edit/null 500 (Internal Server Error)
    에러가 뜨네요.
    
    도움 부탁드립니다~. 정말 감사합니다. 아래에 에러메세지와 코드 올립니다.

    <hr />

    Server running at http://127.0.0.1:8080
    저장완료
    1
    null
    TypeError: D:\work_js\todoapp\views\edit.ejs:21
        19|       <div class="form-group">
        20|         <label>할일</label>
     >> 21|         <!-- <input type="text" value="<%= post._id %>" name="id" style="display: none;"> -->
        22|         <input type="text" value="<%= post._id %>" name="id">
        23|         <input value="<%= post.제목 %>" type="text" class="form-control" name="title">
        24|       </div>
    Cannot read property '_id' of null
        at eval (eval at compile (D:\work_js\todoapp\node_modules\ejs\lib\ejs.js:673:12), <anonymous>:15:31)
        at edit (D:\work_js\todoapp\node_modules\ejs\lib\ejs.js:703:17)
        at tryHandleCache (D:\work_js\todoapp\node_modules\ejs\lib\ejs.js:274:36)
        at View.exports.renderFile [as engine] (D:\work_js\todoapp\node_modules\ejs\lib\ejs.js:491:10)
        at View.render (D:\work_js\todoapp\node_modules\express\lib\view.js:135:8)
        at tryRender (D:\work_js\todoapp\node_modules\express\lib\application.js:657:10)
        at Function.render (D:\work_js\todoapp\node_modules\express\lib\application.js:609:3)
        at ServerResponse.render (D:\work_js\todoapp\node_modules\express\lib\response.js:1039:7)
        at D:\work_js\todoapp\server.js:123:16
        at D:\work_js\todoapp\node_modules\mongodb\lib\utils.js:424:9
    

    <hr />

    const express = require('express');
    const app = express();
    const bodyParser = require('body-parser');
    app.use(bodyParser.urlencoded({extended : true}));
    const MongoClient = require('mongodb').MongoClient;
    const methodOverride = require('method-override');
    app.use(methodOverride('_method'));

    <hr />

    server.js 파일 내용
    

    <hr />

    app.set('view engine', 'ejs');
    app.use('/public', express.static('public'));
    MongoClient.connect('mongodb+srv://@test.rl20r.mongodb.net/test?retryWrites=true&w=majority', { useUnifiedTopology: true }, function(에러, client){
        //연결되면 할일
        if (에러) return console.log(에러);
        db = client.db('todoapp');
        //db.collection('post').insertOne({이름 : 'John', _id : 100, 나이 : 20}, function(에러, 결과){
        //db.collection('post').insertOne({이름 : 'John', 나이 : 20}, function(에러, 결과){
            console.log('저장완료');
        });
        app.listen(8080, function(){
            console.log('Server running at http://127.0.0.1:8080');
        });
    //});
    //app.listen(8080, function(){
    //    console.log('listening on 8080');
    //});
    //누군가가 /pet으로 방문을 하면
    //pet 관련된 안내문을 띄워주자.app
    app.get('/pet', function(요청, 응답){
        응답.send('펫쇼핑');
    });
    app.get('/beauty', function(요청, 응답){
        응답.send('뷰티~');
    });
    app.get('/', function(요청, 응답){
        // 응답.sendFile(__dirname + '/index.html');
        응답.render('index.ejs');
    });
    app.get('/write', function(요청, 응답){
        // 응답.sendFile(__dirname + '/write.html');
        응답.render('write.ejs');
    });
    //어떤 사람이 /add 경로로 POST 요청을 하면.
    //??을 해주세요 
    //어떤 사람이 /add 경로로 POST 요청을 하면.
    //데이터 2개(날짜, 제목)를 보내주는데,
    //이 때, 'post'라는 이름을 가진 collection에 두개 데이터를 저장하기
    //-> add.post('경로', function(){});
    app.post('/add', function(요청, 응답){
        응답.send('전송완료2');
        db.collection('counter').findOne({name : '게시물갯수'}, function(에러, 결과){
            console.log(결과.totalPost);
            var 총게시물갯수 = 결과.totalPost;
            console.log(요청.body.title);
            console.log(요청.body.date);
            db.collection('post').insertOne({_id : 총게시물갯수 + 1, 제목 : 요청.body.title, 날짜 : 요청.body.date}, function(에러, 결과){
                console.log('전송완료3');
                //counter라는 콜렉션에 있는 totalPost라는 항목도 1 증가시켜야함
                db.collection('counter').updateOne({name : '게시물갯수'}, { $inc: {totalPost:1} }, function(에러, 결과){
                    //14강 update와 inc
                    if(에러){return console.log(에러)};
                });
            });
        });
        
        //DB에 저장해주세요
        //웹사이트 기능만들기 기본
        //1. 서버로 데이터 전송할 수 있는 UI만들고
        //2. 서버에서 원하는대로 정보를 처리해주면 됨
    });
    //글번호 달기 기능 만들기
    //list로 GET요청으로 접속하면
    //실제 DB에 저장된 데이터들로 예쁘게 꾸며진 HTML을 보여줌
    app.get('/list', function(요청, 응답){
        //디비에 저장된 post라는 collection안의 모든 데이터를 꺼내주세요.
        db.collection('post').find().toArray(function(에러, 결과){
            console.log(결과);
            응답.render('list.ejs', {posts : 결과});
        });
    });
    app.delete('/delete', function(요청, 응답){
        console.log(요청.body);
        요청.body._id = parseInt(요청.body._id);
        // 요청.body에 담겨온 게시물번호를 가진 글을 db에서 찾아서 삭제해주세요
        // db.collection('post').remove({id : 1});
        db.collection('post').deleteOne(요청.body, function(에러, 결과){
            if(에러){return console.log('삭제 에러')};
            console.log('삭제완료');
            응답.status(200).send({ message : '성공했습니다'});
            // 응답.status(400).send({ message : '실패했습니다'});
        });
    });
    // /detail로 접속하면 detail.ejs 보여줌
    app.get('/detail/:id', function(요청, 응답){
        db.collection('post').findOne({_id : parseInt(요청.params.id)}, function(에러, 결과){
            if(에러){return console.log('디테일 에러')};
            console.log(결과);
            응답.render('detail.ejs', { data : 결과 });
        });
    });
    app.get('/edit/:id', function(요청, 응답){
        db.collection('post').findOne({_id : parseInt(요청.params.id)}, function(에러, 결과){
            console.log(요청.params.id);
                응답.render('edit.ejs', { post : 결과 });
            });
        });
        
        // 폼에 담긴 제목데이터, 날짜데이터를 가지고
        // db.collection 에다가 업데이트함
    app.put('/edit', function(요청, 응답){
        db.collection('post').updateOne({_id : parseInt(요청.body.id)}, { $set : { 제목: 요청.body.title, 날짜: 요청.body.date }}, function(에러, 결과){
            console.log('결과:edit');
            if (결과 == null) {
                console.log(에러);
              } else {
            console.log('수정완료');
            응답.redirect('/list');
              };
        });
    });
    #39186

    codingapple
    키 마스터
    _id가 1인 게시물 수정할 때 /edit/1로 잘 접속해서 수정요청하셨나요
    #39198

    jay
    참가자
    네. http://localhost:8080/edit/1 로 바르게 입력해서, 실행하여 보았습니다.
    mongodb에는 _id 1 과 내용도 잘 있음을 확인했구요. 
    edit.ejs 파일의 아래 부분도 잘 실행되고 있습니다.
    <input type="text" value="<%= post._id %>" name="id">
    1로 표시는 되고 있으나, submit이 안되고 다음으로 넘어가지를 못하고 있습니다.
    
    아마도 소스에 아래 부분을 추가 하고 부터, 오류가 나오는 것 같은데요. 단계를 넘어가기가 힘드네요..
    app.get('/edit/:id', function(요청, 응답){
        db.collection('post').findOne({_id : parseInt(요청.params.id)}, function(에러, 결과){
            console.log(요청.params.id);
                응답.render('edit.ejs', { post : 결과 });
            });
        });
    
    #39200

    codingapple
    키 마스터
    응답.render 전에 console.log(결과) 하면 무엇이 나옵니까 잘나오나요
    #39201

    jay
    참가자
    console.log(결과) 한 줄인데,
    1
    null
    두 줄이 나옵니다.
    
    #39214

    codingapple
    키 마스터
    결과가 null이면 db에 _id :1 인 게시물이 없다는소리입니다 있나 확인해봅시다 
    아니면 _id : '1' 이렇게 되어있을수도요
    #39223

    jay
    참가자
    
    monggodb 쪽도 확인하였는데요. 1 이라고 들어가 있습니다.
    혼자해결하기에 너무 어려워서, 폴더째로 압축해보았습니다. 
    https://drive.google.com/file/d/1pL1lm08-RUyHUYwgopZ_1mZ5BOGKZRZl/view?usp=sharing
    
    #39232

    codingapple
    키 마스터
    </form> 닫는게 2개나 있네요 1개는 지웁시다
    #39240

    jay
    참가자
    감사합니다. 선생님. </form> 1개 지웠습니다.
    재실행해도 에러메세지는 똑같이 뜨는데요. 
    수정에서 submit 버튼이 눌러지지 않고, 
    브라우저 console 창 에러도 똑같고
    
    GET http://localhost:8080/edit/null 500 (Internal Server Error)
    에러메세지도 똑같습니다. 어떻게 해야할까요..
    1
    
    null
    TypeError: D:\work_js\todoapp\views\edit.ejs:21
        19|       <div class="form-group">
        20|         <label>할일</label>
     >> 21|         <!-- <input type="text" value="<%= post._id %>" name="id" style="display: none;"> -->
        22|         <input type="text" value="<%= post._id %>" name="id">
        23|         <input value="<%= post.제목 %>" type="text" class="form-control" name="title">
        24|       </div>
    Cannot read property '_id' of null
     
    #39253

    jay
    참가자
    태그 위치 바꾸어서 해결하였습니다. 감사합니다~
10 글 보임 - 1 에서 10 까지 (총 10 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관, 개인정보처리방침
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠