본문 바로가기

끄적끄적

react mongoDB연결2

전에는 고정된 값이 잘 들어가는지 확인을 하였고 이젠 사용자가 입력하는 값을 받아 POST 요청을 통해 DB로 보내는 과정이다.(GET도 포함)

만들어놓은 코드에 조금만 바꾸면 가능하다.

 

먼저 서버와 MongoDB의 연결부터 해준다. server 폴더로가서 npm start해준다.

//부가적인 코드는 안 올림
app.listen(port, function () {
  console.log('server start on 8008');
});

async function connectHandler() {
  await client.connect();
  console.log('connecting mongo...');
  return 'done';
}
connectHandler()
  .then(console.log('DB연결 완료'))
  .catch((err) => console.log(err));


1. app.post

//   backEnd/index.js
app.post('/api/register', async function (req, res) {
  const db = client.db('Cluster0'); //DB선택
  const collection = db.collection('users'); // collection 선택
  collection.insertOne({ user: req.body.user, pwd: req.body.pwd }); //input에 입력한 값 insert
  console.log('req.body', req.body);
  res.json({ ok: true });
});



//   src/userInput.jsx
const submitHandler = () => {
    const post = {
      user: userId,
      pwd: userPwd,
    };
    fetch('http://localhost:8080/api/register', {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
      },
      body: JSON.stringify(post),
    }).then((res) => {
      console.log('보내기성공');
      res.json();
    });
  };

req.body로 객체 값을 받아와 insertOne을 사용하여 DB에 넣어준다. => 값이 들어가는 것을 확인

 

2. app.get

//    backend/index.js

app.get('/api/register', async function (req, res) {
  const db = client.db('Cluster0');
  const collection = db.collection('users');
  let getLists = await collection.find().toArray();
  console.log(getLists);
  res.send(getLists);
});

//   src/userInput.jsx
  function getUserList() {
    fetch('http://localhost:8080/api/register', {
      method: 'GET',
      headers: {
        'content-type': 'application/json',
      },
    }).then((res) => {
      console.log('보내기성공');
      res.json();
    });
  }
  
  useEffect(() => {
    getUserList();
  }, []);

 

아직까지 client로 가져오는 것을 구상 안했지만(금방 할 예정) 서버에 들어가보면 db의 값을 가져오고 있는 것을 확인할 수 있다.

이제 가져오는 값을 응답값으로해서 받아와 client에서 뿌려주면될꺼같다.

'끄적끄적' 카테고리의 다른 글

react mongoDB연결  (0) 2023.07.05
.env 환경변수 값을 가져오지 못할때  (0) 2023.07.05
서버로 POST 그리고 응답받기  (0) 2023.07.04
react + express + mongoDB  (0) 2023.07.03
git pull --rebase  (0) 2023.06.14