-
글쓴이글
-
2022년 3월 5일 21:02 #28806
김지우참가자강의 너무 잘 듣고 있습니다. 설명하는 능력이 정말 탁월하십니다. 그러나 강의 완강 후 혼자 프로젝트를 이것저것 바꿔나가다 보니 막히는게 많습니다. 밑에 분 글을 참고해서 해결하려고 했지만 잘 되지 않아서 질문드립니다
server.js 에서 mongodb와 연결은 잘 됩니다. listening on 8000 과 listening on db 모두 이상없이 터미널에 뜹니다.
const express = require('express');
const path = require('path');
const app = express();
const MongoClient = require('mongodb').MongoClient
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended : true}));
require('dotenv').config()app.use(express.json());
var cors = require('cors');
app.use(cors());const http = require('http').createServer(app);
http.listen(8000, function () {
console.log('listening on 8000')
});var db; //변수 하나 필요
MongoClient.connect(process.env.DB_URL, {useUnifiedTopology: true }, function(에러, client){
//연결되면 할일
if(에러) return console.log(에러) //에러 나오면 콘솔에 띄우기db = client.db('ShopData'); //ShopData 이라는 db에 연결
console.log('listening on db')});
app.use(express.static(path.join(__dirname, '/build')));
app.get('/', function (요청, 응답) {
응답.sendFile(path.join(__dirname, '/build/index.html'));
});
app.get('*', function (요청, 응답) {
응답.sendFile(path.join(__dirname, '/build/index.html'));
});app.get('/detail', function(요청,응답){
db.collection('Data').find().toArray(function(에러, 결과){
console.log(결과);
응답.send(결과);
})
})
마지막 줄이 문제인 것 같습니다. localhost:8000/detail 의 콘솔에서 아무런 데이터가 뜨지 않고, 응답.send를 응답.json으로 바꿔도 똑같습니다
당연히 여기 React 의 더보기버튼부분에서 저 주소로 get 요청을 하니 콘솔에서는 결과 is not defined 라고 뜹니다. (리액트 프로젝트는 localhost:8001에서 작업하고 있습니다. 원래는 깃헙에 json 파일을 올려 그 주소로 get요청해 사용하고 있었으나 mongodb로 바꾸려고합니다. 사진첨부한대로 mongodb 콜렉션에는 저렇게 데이터를 수십 개 넣었습니다)
Server.js의 문제점 혹은 콜렉션의 문제점, 그리고 아래 코드 React에 저렇게 get 주소 쓰는게 맞는지 여쭤보고 싶습니다.
<button
class="buttonYellow"
style={{width: 85}}
onClick={() => {
axios //axios는 JSON 을 예쁘게 Object 형으로 바꿔줌 즉 따옴표 다 떼줌! fetch는 그런거 없음ㅅㄱ
.get("https://localhost:8000/detail") //get 요청 할 주소
.then((result) => {
//then 은 요청 성공시 실행할 코드, result.data 는 받아온 데이터
hochony변경([...hochony, ...result.data]); //data 카피본에 추가적으로 data2 카피본 넣기
더보기변경(false);
})
.catch(() => {
//catch 는 요청 실패시 실행할 코드
console.log("불러오기 실패!");
console.log(결과);
});
}}
>2022년 3월 6일 14:30 #28855
김지우참가자주말에도 빠른 답변 정말 감사합니다. 말씀대로 하니 localhost:8000/detail 에는 _id 가 포함된 json형태로 데이터가 뜹니다.
하지만 react에서는 여전히 "결과 is not defined" 라고 에러가 뜹니다.
.catch 에서 console.log(결과)를 console.log(result.data)로 바꿔봐도 "result is not defined" 에러가 뜹니다.
<button
class="buttonYellow"
style={{width: 85}}
onClick={() => {
axios //axios는 JSON 을 예쁘게 Object 형으로 바꿔줌 즉 따옴표 다 떼줌! fetch는 그런거 없음ㅅㄱ
.get("https://localhost:8000/detail") //get 요청 할 주소
.then((result) => {
//then 은 요청 성공시 실행할 코드, result.data 는 받아온 데이터
hochony변경([...hochony, ...result.data]); //data 카피본에 추가적으로 data2 카피본 넣기
더보기변경(false);
})
.catch(() => {
//catch 는 요청 실패시 실행할 코드
console.log("불러오기 실패!");
console.log(result.data);
});
}}
>
더보기
</button> : null}그렇다면 hochony 변경([...hochony, ...result.data]) 부분을 어떻게 해야 저 json 데이터를 가져와 사용할 수 있을까요?
hochony변경은 이렇게 사용하고 있습니다
let [hochony, hochony변경] = useState(Data); //Data 는 data.js 파일 데이터
//data.js 파일 내용
export default [
{
id: 0,
title: "This is my seat",
content: "Go get my snack then I will move",
price: 12000,
quan: 100
},{
id: 1,
title: "Eat my feet human",
content: "It is not high five",
price: 11000,
quan: 100
},{
id: 2,
title: "Too bright here",
content: "But still I can hear you",
price: 13000,
quan: 100
},
];2022년 3월 6일 14:44 #28856
김지우참가자.get("https://localhost:8000/detail")
에서 저 링크 ctrl 클릭 해보니 연결할 수 없다고 하는데 이게 문제인 것 같기도 합니다
제가 cors를 제대로 설치하지 않아서 인걸까요?
server.js 파일에 cors 이렇게 써넣고 npm install cors 로 설치도 했습니다
app.use(express.json());
var cors = require('cors');
app.use(cors()); //nodejs 와 react 사이 ajax 요청 사용하기package.json 파일에 이렇게 proxy도 써넣었습니다.
{
"name": "shop",
"version": "0.1.0",
"private": true,
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^1.3.0",
"@fortawesome/free-brands-svg-icons": "^6.0.0",
"@fortawesome/free-regular-svg-icons": "^6.0.0",
"@fortawesome/free-solid-svg-icons": "^6.0.0",
"@fortawesome/react-fontawesome": "^0.1.17",
"@testing-library/jest-dom": "^5.16.1",
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^13.5.0",
"axios": "^0.25.0",
"babel-plugin-macros": "^3.1.0",
"bootstrap": "^5.1.3",
"cors": "^2.8.5",
"dotenv": "^16.0.0",
"express": "^4.17.3",
"mongodb": "^4.4.0",
"node-sass": "^7.0.1",
"react": "^17.0.2",
"react-bootstrap": "^2.1.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.6",
"react-router-dom": "^5.3.0",
"react-scripts": "5.0.0",
"react-transition-group": "^4.4.2",
"redux": "^4.1.2",
"styled-components": "^5.3.3",
"web-vitals": "^2.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:8000/"
}2022년 3월 6일 23:24 #28879
codingapple키 마스터서버에서 응답.send() 말고 응답.json(데이터) 이렇게 보내봅시다
근데 https:// 가 아니라 http:// 같군요
2022년 3월 7일 16:24 #28923
김지우참가자잘 해결되었습니다! 감사합니다!
그런데 이 프로젝트를 github-pages 로 열어서 더보기 기능을 사용하려니 다시 작동하지 않습니다.
아마 localhost:8000이 항상 열려있어야 할 텐데, 이를 해결할 수 있는 방법이 있나요?
이전에는 수업에서 쓰셨던 방법처럼 github에 json파일을 올려서 그 링크를 사용했지만, mongodb는 어떻게 collection 링크를 가져올 수 있는지 여쭤보고 싶습니다.
2022년 3월 7일 22:10 #28949
codingapple키 마스터server.js 파일을 24시간 실행중인 컴퓨터가 필요합니다
그래서 aws나 구글클라우드 이런거 쓰는 방법밖에 없습니다
-
글쓴이글
- 답변은 로그인 후 가능합니다.