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

home2 게시판 Node.js, Express 게시판 로그인 마이페이지로 가질 않습니다

로그인 마이페이지로 가질 않습니다

2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 글쓴이
  • #54753

    윤정현
    참가자
    로그인 안됐을때 mypage로 가는거 차단은 잘 되는데 막상 로그인하고 마이페이지로 가려니 오류가 뜹니다.
    콘솔창에는
    function deserialized(e, u) {
          pass(i + 1, e, u);
        }
    
    해당 문구가 뜨고요
    
    코드 첨부합니다
    
    
    
    
    
    
     
    const express = require('express');
    const app = express();
    app.set('view engine', 'ejs');
    app.use(express.urlencoded({
      extended: true
    }));
    //몽고db
    const MongoClient = require('mongodb').MongoClient;
    //put 메소드 쓰기위한 설정
    const methodOverride = require('method-override')
    app.use(methodOverride('_method'))
    //static 설정
    app.use('/public', express.static('public'));
    var db;
    MongoClient.connect('mongodb+srv://yun6160:@cluster0.bu5yz.mongodb.net/todoapp?retryWrites=true&w=majority', function (에러, client) {
      if (에러) {
        return console.log(에러)
      }
      db = client.db('todoapp');
      app.listen(8081, function () {
        console.log('listening on 8081')
        //서버 실행 : nodemon server.js
      });
    })
    // 여기까지 서버 띄우기 위한 기본 셋팅
    app.get('/', function (요청, 응답) {
      응답.render('index.ejs');
    });
    // get 함수는 파라미터 두개 받는데 그게 하나는 '/'고 하나는 function(){}
    // 이때 function(){} 은 함수안의 함수라 콜백함수라고 함 -> 순차적으로 실행하고 싶을때 
    // .get('경로', function(요청내용, 응답할 방법){})
    app.get('/write', function (요청, 응답) {
      응답.render('write.ejs');
    });
    app.post('/add', function (요청, 응답) {
      // findeOne : db에서 항목을 찾는다
      db.collection('counter').findOne({
        name: '게시물갯수'
      }, function (에러, 결과) {
        console.log(결과.totalPost)
        var 총게시물갯수 = 결과.totalPost;
        // 오브젝트 데이터타입으로 자료 저장
        db.collection('post').insertOne({
          _id: 총게시물갯수 + 1,
          할일: 요청.body.todo,
          날짜: 요청.body.startdate
        }, function (에러, 결과) {
          console.log('저장완료');
          // totalPost 라는 항목도 1증가 updateOne : 하나를 수정하고 싶다
          db.collection('counter').updateOne({
            name: '게시물갯수'
          }, {
            $inc: {
              totalPost: 1
            }
          }, function (에러, 결과) {
            if (에러) {
              return console.log(에러)
            } else {
              응답.redirect('/list')
            }
          })
        });
      });
      console.log(요청.body.todo)
      console.log(요청.body.startdate)
    });
    app.get('/list', function (요청, 응답) {
      db.collection('post').find().toArray(function (에러, 결과) {
        응답.render('list.ejs', {
          posts: 결과
        });
      });
      //파일명 post인 애들 모두 찾아주세요
      // 1. DB에서 자료 찾아주세요
      // 2. 찾은걸 ejs 파일에 집어넣어주세요
    });
    app.delete('/delete', function (요청, 응답) {
      console.log(요청.body)
      요청.body._id = parseInt(요청.body._id); // 정수로 변환
      db.collection('post').deleteOne(요청.body, function (에러, 결과) {
        console.log('삭제완료');
        응답.status(200).send(
          "성공"
        );
        // 응답 코드 200를 보내주세요~ 응답 200 : 성공했음
        // 1차적으로 숫자로 요청했지만 문자로 받아서 삭제가 안됨
      });
    });
    app.get('/detail/:id', function (요청, 응답) {
      //: 슬래시 뒤에 문자열을 붙였을때 실행해달라
      db.collection('post').findOne({
        //아이디가 ?? 인걸 찾아옴
        _id: parseInt(요청.params.id)
      }, function (에러, 결과) {
        console.log(결과)
        if (결과 == null) {
          return console.log('결과가 없습니다.');
        } else {
          응답.render('detail.ejs', {
            data: 결과
          });
        }
      })
    });
    app.get('/edit/:id', function (요청, 응답) {
      db.collection('post').findOne({
        //아이디가 ?? 인걸 찾아옴
        _id: parseInt(요청.params.id)
      }, function (에러, 결과) {
        console.log(결과)
        if (결과 == null) {
          return console.log('결과가 없습니다.');
        } else {
          응답.render('edit.ejs', {
            data: 결과
          });
        }
      })
      
    });
    //put으로 수정
    app.put('/edit', function(요청, 응답){
      console.log(요청.body)
      db.collection('post').updateOne({
        _id : parseInt(요청.body.numId)
      },{
        $set : {할일 : 요청.body.todo}
      }, function(에러, 결과){
        응답.redirect('/list')
      })
    })
    //session 방식 로그인 구현
    const passport = require('passport');
    const LocalStrategy = require('passport-local').Strategy;
    const session = require('express-session');
    //미들웨어: 요청과 응답 중간에 시행되는 코드
    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('/login', passport.authenticate('local', {
      //인증 실패했을때 fail 로 리다이렉트
      failureRedirect : '/fail'
    }), function(요청, 응답){
      응답.redirect('/');
    });
    app.get('/fail', function(요청, 응답){
      응답.render('login.ejs');
    });
    app.get('/mypage',로그인했니,function(요청, 응답){
      응답.render('mypage.ejs');
    });
    function 로그인했니(요청, 응답, next){
      if(요청.user){
        next() //통과시켜주세요
      }else{
        응답.send('로그인 ㄴㄴ');
      }
    }
    passport.use(new LocalStrategy({
      usernameField: 'id',
      passwordField: 'pw',
      session: true,
      passReqToCallback: false,
    }, function (입력한아이디, 입력한비번, done) {
      db.collection('login').findOne({ id: 입력한아이디 }, function (에러, 결과) {
        if (에러) return done(에러)
        if (!결과) return done(null, false, { message: '없는 아이디입니다.' })
        if (입력한비번 == 결과.pw) {
          return done(null, 결과) //done(서버에러, 성공시 사용자 DB데이터, 에러메세지)
        } else {
          return done(null, false, { message: '비밀번호를 확인해주세요.' })
        }
      })
    }));
    //세션으로 저장(로그인 성공시 발동)
    passport.serializeUser(function(user, done){
      done(null, user.id)
    });
    //이 세션 데이터를 가진 사람을 DB에서 찾아주세요(마이페이지 접속시 발동)
    passport.deserializeUser(function(아이디, done){
      done(done, {})
    });
    
    
    
    
    #54755

    윤정현
    참가자
    passport.deserializeUser(function(아이디, done){
      done(done, {})
    });
    
    해당 에 done이 아니라 null로 작성하니 되네요... 이거 차이가... 이렇게 크다니...
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
  • 답변은 로그인 후 가능합니다.

About

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

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

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