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

home2 게시판 Node.js, Express 게시판 node react 연동 시 데이터를 어떻게 가져오나요..?

node react 연동 시 데이터를 어떻게 가져오나요..?

6 글 보임 - 11 에서 16 까지 (총 16 중에서)
  • 글쓴이
  • #27628

    codingapple
    키 마스터

    axios쓸 땐 result가 아니라 result.data에 데이터가 담겨있습니다

    리액트에선 result.data.post 출력해보면 됩니다

    이상한 html이 들어있으면 res.send 말고 res.json(데이터) 이걸로 보내봅시다 

    #27630

    이지현
    참가자

    app.get('/products', function (req, res) {
      db.collection('posts').find().toArray(function (err, result) {
        res.json({ post: result.data });
        console.log(result.data);
      });
    });

        useEffect(() => {
            axios.get('http://localhost:8080/products').then((result) => {
                dataSet([...result.data.post])
                console.log(result.data.post)
            })
        }, [])

     

    이렇게 해봤는데 

    Products.js:16 Uncaught (in promise) TypeError: result.data.post is not iterable

    이런 오류가 뜨고

    dataSet([...result.data])

    console.log(result.data.post)

    이렇게 하면 undefined가 뜹니다

     

    res.json({ post: result });으로 해봐도 똑같아요...

    그리고 서버 콘솔창엔 여전히 아무 것도 안 뜹니다... ㅜㅜ

     

    #27644

    codingapple
    키 마스터

    서버에서는 result.data가 아니라 result 안에 담겨있습니다 

    result안에 아무것도 없으면 posts라는 컬렉션이없거나 안에 document가 없거나 그런 경우입니다 

    #27677

    이지현
    참가자

    db가 잘못됐나 해서 전에 강의 보면서 만든 다른 node.js 파일에  posts 출력해봤는데 거기서는 되는데 

    이상하게 이 파일에서만 서버 콘솔창 출력이 안돼요...

    하나하나 비교해가면서 봤는데도 도저히 뭐가 잘못된건지 모르겠어요 ㅜㅜ .env도 따로 빼서 만들었는데 

     

    const express = require('express');
    const path = require('path');
    const app = express();

    const http = require('http').createServer(app);

    app.use(express.json());
    const cors = require('cors');
    app.use(cors());

    app.use(express.urlencoded({ extended: true }));

    require('dotenv').config()

    // react 연결
    app.use(express.static(path.join(__dirname, 'carrot-clone/build')))

    app.get('/', function (요청, 응답) {
      응답.sendFile(path.join(__dirname, 'carrot-clone/build/index.html'))
    })

    app.get('*', function (요청, 응답) {
      응답.sendFile(path.join(__dirname, 'carrot-clone/build/index.html'));
    });

    // mongoDB 연결
    const MongoClient = require('mongodb').MongoClient;

    let db;

    MongoClient.connect(process.env.DB_URL, function (err, client) {
      // 연결되면 할 일
        if (err) { return console.log(err) }// MongoDB 관련된 함수들 전부 콜백함수에서 에러처리가능

        db = client.db('carrot');

        http.listen(process.env.PORT, function () {
            console.log('listening on 8080')
        });

    })

    let multer = require('multer');

    let storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, './public/img')// public/img 폴더 안에 이미지가 저장됨
      },
      filename: function (req, file, cb) {
        cb(null, file.originalname + ' - ' + new Date().toISOString().replace(/:/g, '-'))// 저장한 이미지의 파일명 설정
      }
    });

    let upload = multer({ storage: storage });// 이미지 업로드 시 multer를 미들웨어로 동작시키기

    app.post('/image-upload', upload.single('img'), function (req, res) {
      res.redirect('/upload');
    })

    app.get('/img/:imageName', function (req, res) {
      res.sendFile(__dirname + '/public/img/' + req.params.imageName)// __dirname: 현재 파일경로
    })

    app.post('/upload', function (req, res) {
      db.collection('counter').findOne({ name: '게시물개수' }, function (err, result) {
        let 총게시물개수 = result.totalPost;
        let 저장할거 = { _id: 총게시물개수 + 1, title: req.body.title, price: req.body.price, text: req.body.text, category: req.body.category }

        db.collection('posts').insertOne(저장할거, function (err, result) {
          console.log('저장완료')
          console.log(req.body)
        })

        db.collection('counter').updateOne({ name: '게시물개수' }, { $inc: { totalPost: 1 } }, function (err, result) {
          //  { $set: { 바꿀 값 }}
          //  { $inc: { 기존 값에 더해줄 값 }}
          if (err) { return console.log(err) }
        })
        res.redirect('/products')
      })
    })

    app.get('/products', function (req, res) {
      db.collection('posts').find().toArray(function (err, result) {
        console.log(result);
        res.json({ post: result });
      });
    });

     

    혹시 잘못된게 있을까요?? 자꾸 질문해서 죄송합니다... 몇 주째 이것때문에 진행이 안돼서요 ㅜㅜ

    #27694

    codingapple
    키 마스터

    app.get('*',

    라우트를 다른것들 밑으로 내려봅시다

    #27704

    이지현
    참가자

    그렇게 하니까 바로 되네요!!!!

    감사합니다~!!!

6 글 보임 - 11 에서 16 까지 (총 16 중에서)
  • 답변은 로그인 후 가능합니다.

About

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

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

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