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

home2 게시판 Node.js, Express 게시판 TypeError: Cannot read properties of undefined (reading 'name')

TypeError: Cannot read properties of undefined (reading 'name')

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

    임규연
    참가자
    에러는 아래와 같습니다
    ~~~~~ /routes/delete.js:20
          if (응답.user.name === posting.name) {
                      ^
    TypeError: Cannot read properties of undefined (reading 'name')
    
    상황을 설명하자면 routes/delete.js로 삭제기능을 라우터로 분리하였는데
     로그인 상황 체크하는 미들웨어를 넣었음에도 불구하고 응답.user가 정의가 안되어있다네요
    아래는 코드입니다
    
    routes/delete.js
    
    
    const router = require('express').Router()
    let connectDB = require('./../db.js')
    const { ObjectId } = require('mongodb');
    let checkLogin = require('../utils/checkLogin.js');
    let db
    connectDB.then((client)=>{
    console.log('DB연결성공')
    db = client.db('forum')
    }).catch((err)=>{
    console.log(err)
    })
    router.delete('/', checkLogin, async(요청, 응답) => {
    let posting = await db.collection('post').findOne({_id : new ObjectId(요청.query.id)});
     
    if (posting != null) {
    console.log (응답.user)
    if (응답.user.name === posting.name) {
    await db.collection('post').deleteOne({_id : new ObjectId(요청.query.id)});
    }
     
    else {
    if (응답.user.name !== posting.name) {
    응답.send("<script>alert('다른 사용자의 글을 삭제할 수 없습니다.'); history.back()</script>");
    }
    }
    }
     
    else {
    응답.send("<script>alert('해당하는 게시물이 없습니다.'); window.location.replace('/list/1');</script>");
    }
    });
    module.exports = router
    utils/checkLogin.js
    
    function checkLogin(요청, 응답, next) {
    if (요청.user === undefined) {
    응답.send("<script>alert('로그인이 필요합니다.'); window.location.replace('/login');</script>");
    }
    else {
    next();
    }
    }
    module.exports = checkLogin;
    
    
    
    
    • 이 게시글은 임규연에 의해 1 년, 3 월 전에 수정됐습니다.
    #119050

    임규연
    참가자
    해결되었습니다. 요청.user인데 응답.user로 했네요.
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 호 / 개인정보관리자 : 박종흠