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

home2 게시판 Node.js, Express 게시판 Database에 자료 저장하는 법 (한줄이면 끝) 강의 문의

Database에 자료 저장하는 법 (한줄이면 끝) 강의 문의

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

    오준석
    참가자
    안녕하세요. 강의 잘 듣고 있습니다! 막히는 부분이 있어 질문 드립니다.
    
    Database에 자료 저장하는 법 (한줄이면 끝) 강의를 듣고 코드를 완성한 후에 실행을 해봤는데, 홈페이지 몽고DB Atlas에 데이터가 반영되지 않아 제가 코드를 실수한 부분이나 놓치고 있는 부분이 있는지 여쭈고자 문의드립니다.
    
    아래와 같이 정상적으로 실행은 되었습니다. 
    [nodemon] restarting due to changes...
    [nodemon] starting `node server.js`
    (node:11144) Warning: Accessing non-existent property 'MongoError' of module exports inside circular dependency    
    (Use `node --trace-warnings ...` to show where the warning was created)
    listening on 8080
    저장완료
    아래는 server.js 입니다. 
    ```
    const express = require('express')
    const app = express()
    const bodyParser= require('body-parser')
    app.use(bodyParser.urlencoded({extended: true}))</pre>
    const MongoClient = require('mongodb').MongoClient;
    app.set('view engine', 'ejs');</pre>
    var db;
    MongoClient.connect('mongodb+srv://admin:qwer1234@cluster0.p7hon5t.mongodb.net/?retryWrites=true&w=majority', 
    { useUnifiedTopology: true }, function(에러, client) {
      // 연결되면 할일
      if(에러) return console.log(에러)
      db = client.db('todoapp');</pre>
    db.collection('post').insertOne( {이름 : 'John', _id : 100} , function(에러, 결과){
        console.log('저장완료'); 
      });
    app.listen(8080, function() {
        console.log('listening on 8080')
    });
    
    
    app.get('/', function(요청, 응답) { 
      응답.sendFile(__dirname +'/index.html')
    })
    app.get('/write', function(요청, 응답) { 
        응답.sendFile(__dirname +'/write.html')
    });
    app.post('/add', function(요청, 응답){
      console.log(요청.body);
      응답.send('전송완료')
      // DB에 저장해주세용 
    });
    app.post('/add', function(요청, 응답){
      응답.send('전송완료');
      db.collection('post').insertOne( { 제목 : 요청.body.title, 날짜 : 요청.body.date } , function(){
        console.log('저장완료')
      });
    });
    // /list 로 GET요청하면 실제 DB에 저장된 데이터들로 예쁘게 꾸며서 HTML을 보여줌
    app.get('/list', function(요청, 응답){
      응답.render('list.ejs');
    })
    ```
     
     
     
     
     
    #88011

    codingapple
    키 마스터
    app.post('/add 2개 있는데 위에건 지웁시다 
    응답.send는 insertOne 콜백함수안으로 옮깁시다
    #88017

    오준석
    참가자
    1111
    말씀하신 대로 아래와 같이 수정해 보았는데, 데이터가 들어오지 않습니다. 코드 문제는 없고, 다른 문제일까요?
    ```
    </pre>
    <pre>const express = require('express')
    const app = express()
    const bodyParser= require('body-parser')
    app.use(bodyParser.urlencoded({extended: true}))</pre>
    <pre>const MongoClient = require('mongodb').MongoClient;
    app.set('view engine', 'ejs');</pre>
    <pre>var db;
    MongoClient.connect('mongodb+srv://admin:qwer1234@cluster0.p7hon5t.mongodb.net/?retryWrites=true&w=majority', 
    { useUnifiedTopology: true }, function(에러, client) {
      // 연결되면 할일
      if(에러) return console.log(에러)
      db = client.db('todoapp');</pre>
    <pre>  db.collection('post').insertOne( {이름 : 'John', _id : 100} , function(에러, 결과){
        console.log('저장완료'); 
      });</pre>
    <pre>  app.listen(8080, function() {
        console.log('listening on 8080')
    });
    });</pre>
    <pre>app.get('/', function(요청, 응답) { 
      응답.sendFile(__dirname +'/index.html')
    })</pre>
    <pre>app.get('/write', function(요청, 응답) { 
        응답.sendFile(__dirname +'/write.html')
    });</pre>
    <pre>app.post('/add', function(요청, 응답){
      db.collection('post').insertOne( { 제목 : 요청.body.title, 날짜 : 요청.body.date } , function(){
        응답.send('전송완료');
        console.log('저장완료')
        
      });
      
    });</pre>
    <pre>// /list 로 GET요청하면 실제 DB에 저장된 데이터들로 예쁘게 꾸며서 HTML을 보여줌
    app.get('/list', function(요청, 응답){
      응답.render('list.ejs');
    })</pre>
    <pre>```
    #88041

    codingapple
    키 마스터
    /add로 post요청 잘 보내고있나 
    /add로 post요청하면 저장완료 출력잘되나 확인해봅시다
    #88077

    오준석
    참가자
    post요청이 받아지지 않습니다. 따로 확인해보도록 하겠습니다. 답변 감사합니다.
     
5 글 보임 - 1 에서 5 까지 (총 5 중에서)
  • 답변은 로그인 후 가능합니다.

About

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

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

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