-
글쓴이글
-
2022년 2월 11일 10:19 #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)
})
}, [])이렇게 작성했는데 어떤 부분을 고쳐야 할까요..>??? ㅠㅠ
2022년 2월 14일 23:44 #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이런 오류 뜨는데 위치를 잘못 넣은 걸까요?
2022년 2월 15일 10:41 #27334
이지현참가자let [data, dataSet] = useState([]);
useEffect(() => {
axios.get('http://localhost:8080/products').then((result) => {
dataSet([...result.data])
console.log(result.data)
})
}, [])그래ㅑ도 안돼요 ㅠㅠ
2022년 2월 15일 12:49 #27345
codingapple키 마스터저거는 class 컴포넌트네요 그 안에선 use어쩌구 함수들 사용이 불가능합니다
function 컴포넌트로 바꿉시다
2022년 2월 15일 17:46 #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 출력해보면
이렇게 나와서 저거 다 펼쳐봐서 봤는데 데이터가 어디있는지도 모르겠어요...
2022년 2월 17일 20:06 #27568
codingapple키 마스터app.use(express.json()); 를 서버파일 상단쯤에 추가합시다
브라우저에서 출력해볼 때 result.data 출력해보면됩니다 거기 데이터가 담겨있습니다
서버에서 result 출력해봐도 데이터들이 잘 담겨있는지 확인합시다
2022년 2월 18일 10:27 #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
아예 오류가 뜹니다...
-
글쓴이글
- 답변은 로그인 후 가능합니다.