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

home2 게시판 Node.js, Express 게시판 node.js /list 페이지 관련 질문입니다.

node.js /list 페이지 관련 질문입니다.

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

    Choi BI
    참가자
    하루 종일 리서치, 수정해봤는데도 답이 안나와 질문 드립니다ㅠ
    아래처럼 코드를 작성해서 http://localhost:8000/list 페이지로 이동할 경우,
    무한 로딩 현상이 일어나면서 페이지 이동이 안되는데 이유가 뭘까요..?
    
    
    const express = require("express");
    const app = express();
    const bodyParser = require("body-parser");
    app.use(bodyParser.urlencoded({ extended: true }));
    const MongoClient = require("mongodb").MongoClient;
    app.set("view engine", "ejs");
    app.listen(8000, function () {
      console.log("연결완료");
    });
    var db;
    MongoClient.connect(
      "mongodb+srv://qldnjs23:<비밀번호>@cluster0.am3ri5e.mongodb.net/?retryWrites=true&w=majority"
    )
      .then(function (client) {
        db = client.db("todoapp"); // db 변수에 DB 연결 객체 할당
        console.log("DB 연결 완료");
      })
      
      .catch(function (err) {
        console.log(err);
      });
      app.get("/list", function (req, res) {
        db.collection("post")
          .find()
          .toArray(function (error, result) {
            console.log(result);
            res.writeHead(200, {"Content-Type": 'text/html;charset=UTF-8'});
            res.render("list.ejs", { posts: result });
          });
      });
    app.get("/write", function (req, res) {
      res.sendFile(__dirname + "/write.html");
    });
    app.post("/add", function (req, res) {
      res.send("전송완료");
      db.collection("post").insertOne(
        { title: req.body.title, pw: req.body.pw },
        function (에러, 결과) {
          console.log(req.body.title);
          console.log(req.body.pw);
          console.log("저장완료");
        }
      );
    });
    app.get("/beauty", function (req, res) {
      res.send("beauty page");
    });
    감사합니다.
    
    
    #81688

    Choi BI
    참가자
    app.get("/list", function (req, res) 부분에 아래와 같은 오류가 뜨긴 합니다..
    TypeError: Cannot read properties of undefined (reading 'collection')
    #81752

    codingapple
    키 마스터
    app.get("/list", 코드를 MongoClient.connect 바깥으로 뺍시다
    #89797

    손유정
    참가자
    같은 증상입니다. app.get('list'~~~) 코드가 이미 밖에 나와있는데 무한로딩되며 실행이 안됩니다.
    db에 데이터 4개 정상 저장되어있고, write에서 추가 잘됩니다.
    
    
    const express = require('express')
    const app = express()
    const bodyParser = require('body-parser');
    app.use(express.urlencoded({extended : true}));
    const mongodb = require('mongodb')
    const MongoClient = mongodb.MongoClient;
    const url = 'mongodb+srv://admin:qwer1234@cluster1.eiwfukf.mongodb.net/?retryWrites=true&w=majority'
    var db;
    //ejs 쓸거임 추가
    app.set('view engine', 'ejs');
    //----------------------------------------------------//
    MongoClient.connect(url)
        .then(client => {
            db=client.db('todoapp');
            console.log('connected');
            // console.log(client);
        })
        .then(app.listen(8080, () => {
            console.log('listening on 8080');
        }));
        
        
    /**index.html 실행 코드 */
    app.get('/', function(req,res) {
        res.sendFile(__dirname + '/index.html')
    });
    /** 누군가가 /pet으로 방문을 하면 pet 관련한 안내문을 띄워주자 */
    app.get('/pet',  function(req, res){
        res.send('펫이다')
    });
    app.get('/beauty', function(req,res){
        res.send('뷰티다')
    }) ;
    app.get('/write', function(req,res){
        res.sendFile(__dirname + '/write.html')
    });
    app.post('/add', function(req,res){
        db.collection('post').insertOne({title:req.body.title, date:req.body.date}, function(err, result){
        })
        res.send('전송시마이');
        console.log(req.body.title)
        console.log(req.body.date)
    });
    /**
     * /list 로 get 요청으로 접속하면
     * 실제 DB에 저장된 데이터들로 꾸며진 html을 보여줌
     * 
     */
    app.get('/lists', function(req, res){
        /**db에 저장된 post 라는 collection 안의 모든 데이터를 꺼내주세요 */
        db.collection('post').find().toArray(function(err, result){
            console.log(result);
            // res.render('list.ejs', {posts : result});
        });
    });
    #89825

    codingapple
    키 마스터
    /lists로 접속해도 안됩니까
    #89827

    손유정
    참가자
    안됩니다 list일 때 무한 로딩이라서 lists로 바꾸고 다시 해봤던 것이었습니다. 역시나 무한로딩입니다...
    #89903

    codingapple
    키 마스터
            // res.render('list.ejs', {posts : result}); 주석은 해제합시다 
    
    #89930

    손유정
    참가자
    넵 주석 없이 했을 때 안되어서 주석처리 해보았던 것인데 다시 주석지우고 해도 안됩니다 ㅜ
    무한로딩입니다 (최소10분 이상)
    
    오류의 대부분은 오타이지만 6개월 전에 정상작동했던 코드 복붙해도 안되니 오타가 아니라 다른 원인인 듯 합니다...
    
    #89964

    codingapple
    키 마스터
    복붙해보니까 /lists 접속 잘되는데 
    npm install ejs 했는지 views폴더에 list.ejs있나 확인해봅시다
    #90139

    손유정
    참가자
    혹시나해서 npm install ejs 다시 한 번 더 하고 views에 잘 있는지도 봤는데
    역시 무한로딩입니다(크롬, 웨일, 엣지 브라우저 같은 증상) ㅎㅎ
    혹시 개발 환경을 새로 세팅하고 실행해보려 하는데
    npm을 초기화하면 될까요..
    
    제목 없음
10 글 보임 - 1 에서 10 까지 (총 12 중에서)
  • 답변은 로그인 후 가능합니다.

About

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

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

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