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

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

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

10 글 보임 - 1 에서 10 까지 (총 16 중에서)
  • 글쓴이
  • #27016

    이지현
    참가자

    /products 페이지로 posts 컬렉션 데이터를 data라는 이름으로 보내려 하는데 계속 

    Products.js:12 Uncaught ReferenceError: Cannot access 'data' before initialization

    이런 오류가 나네요 ㅠㅠ

    다른 분들 질문을 봐도 모르겠어요... 

    <server.js - 노드 파일>

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

    <Products.js - 리액트 파일>

            let [data, dataSet] = [{ data }];

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

     

    이렇게 작성했는데 어떤 부분을 고쳐야 할까요..>??? ㅠㅠ

    #27054

    codingapple
    키 마스터

    let [data, dataSet] = [];

    이건 초기값이 없으면 비워놔도 될듯요 

    #27301

    이지현
    참가자

    <server.js - 노드 파일>

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

    <Products.js - 리액트 파일>

    class Products extends Component {
        render() {

            let [data, dataSet] = [];

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

            return (
                <div className="products">
                </div>
            )
        }
    }

    이렇게 했는데 계속 오류나네요... 

    hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
    1. You might have mismatching versions of React and the renderer (such as React DOM)
    2. You might be breaking the Rules of Hooks
    3. You might have more than one copy of React in the same app

     

    이런 오류 뜨는데 위치를 잘못 넣은 걸까요?

     

    #27323

    codingapple
    키 마스터

    let [data, dataSet] = useState( []);

    useState가 빠진듯요 

    #27334

    이지현
    참가자

            let [data, dataSet] = useState([]);

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

     

    그래ㅑ도 안돼요 ㅠㅠ

    #27345

    codingapple
    키 마스터

    저거는 class 컴포넌트네요 그 안에선 use어쩌구 함수들 사용이 불가능합니다

    function 컴포넌트로 바꿉시다 

    #27382

    이지현
    참가자

    자꾸 질문해서 죄송합니다...

    <server.js - 노드 파일>

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

    <Products.js - 리액트 파일>

        let [data, dataSet] = useState([]);

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

        return (
            <div>
            </div>
        )

    }

     

    말씀해주신대로 이렇게 해서 오류는 잡았는데

    어떻게

     

    이 데이터를 가져와야할 지 모르겠어요...

    이리저리 해봐도 계속 다른 것만 나오네요

    콘솔창에 result 출력해보면

    이렇게 나와서 저거 다 펼쳐봐서 봤는데 데이터가 어디있는지도 모르겠어요...

    #27559

    이지현
    참가자

    혹시... 제 질문 누락됐을까요??

    #27568

    codingapple
    키 마스터

    app.use(express.json()); 를 서버파일 상단쯤에 추가합시다 

    브라우저에서 출력해볼 때 result.data 출력해보면됩니다 거기 데이터가 담겨있습니다

    서버에서 result 출력해봐도 데이터들이 잘 담겨있는지 확인합시다 

    #27618

    이지현
    참가자

     

    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 }));

    // 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('mongodb+srv://admin:1234@cluster0.mutky.mongodb.net/carrot?retryWrites=true&w=majority', function (err, client) {
      // 연결되면 할 일
      if (err) { return console.log(err) }// MongoDB 관련된 함수들 전부 콜백함수에서 에러처리가능

      db = client.db('carrot')

      http.listen(8080, 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.send({ post: result });
      });
    });

     

    이게 전체 코드인데 /products에 접속해봐도 result 출력이 안되네요...

     

        let [post, dataSet] = useState([]);

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

     

    data를 post로 바꿨더니

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

    아예 오류가 뜹니다...

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

About

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

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

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