-
글쓴이글
-
2022년 2월 18일 12:48 #27628
codingapple키 마스터axios쓸 땐 result가 아니라 result.data에 데이터가 담겨있습니다
리액트에선 result.data.post 출력해보면 됩니다
이상한 html이 들어있으면 res.send 말고 res.json(데이터) 이걸로 보내봅시다
2022년 2월 18일 13:23 #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 });으로 해봐도 똑같아요...
그리고 서버 콘솔창엔 여전히 아무 것도 안 뜹니다... ㅜㅜ
2022년 2월 18일 15:52 #27644
codingapple키 마스터서버에서는 result.data가 아니라 result 안에 담겨있습니다
result안에 아무것도 없으면 posts라는 컬렉션이없거나 안에 document가 없거나 그런 경우입니다
2022년 2월 18일 23:33 #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 });
});
});혹시 잘못된게 있을까요?? 자꾸 질문해서 죄송합니다... 몇 주째 이것때문에 진행이 안돼서요 ㅜㅜ
-
글쓴이글
- 답변은 로그인 후 가능합니다.