리액트와 Node.js를 연결해서 백엔드에 데이터 가져오기
CORS : 교차 출처 리소스 공유를 뜻하며, 한 출처에서 실행 중인 웹 애플리케이션이 다른 출처의 자원에 접근할 수 있는 권한을 부여하도록 브라우저에 알려주는 체제
-백엔드-
controllers - <cantactController-2.js>
(...)
//Get all contact, /contact
const getAllContact = asynchHandler(async (req, res) => {
const contact = await Contact.find();
const users = [ //임시 데이터
{ name: "John", email: "john@aaa.bbb", phone: "123456789" },
{ name: "Jane", email: "jane@aaa.bbb", phone: "987654321" },
];
res.status(200).send(users);
});
(...)
routes - <contactRoutes-2.js>
const express = require("express");
const router = express.Router();
const {
getAllContact,
createContect,
getContact,
updateContact,
deleteContact,
} = require("../controllers/contactController-2"); //contactController-2.js과 연결
router.route("/").get(getAllContact).post(createContect);
router.route("/:id").get(getContact).put(updateContact).delete(deleteContact);
module.exports = router;
<app-2.js> : CORS를 셋팅
>> npm install cors
const express = require("express");
const dbConnect = require("./config/dbConnect");
const cors = require("cors"); //CORS 연결
const app = express();
dbConnect();
app.use(cors()); //CORS 셋팅
app.get("/", (req, res) => {
res.status(200).send("Hello Node");
});
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/contact", require("./routes/contactRoutes-2")); //contactRoutes-2.js과 연결
app.listen(8080, () => { //8080 포트로 설정
console.log("8080 포트에서 서버 실행 중");
});
-프론트엔드-
<App.js> : 임시 데이터 출력
import React, { useEffect, useState } from "react";
function App() {
const [texts, setTexts] = useState([]);
useEffect(() => { //localhost:8080/contact와 연결
fetch("http://localhost:8080/contact")
.then((res) => res.json())
.then((data) => setTexts(data));
});
return (
<div>
{texts.map((text, index) => {
return (
<p key={index}>
이름: {text.name}, 이메일: {text.email}, 번호: {text.phone}
</p>
);
})}
</div>
);
}
export default App;
'Do it Node.js > React BackEnd' 카테고리의 다른 글
6. 로그인 페이지 (0) | 2024.03.20 |
---|---|
5. 회원가입 페이지 (0) | 2024.03.19 |
4. 연락처 수정 페이지, 삭제 (0) | 2024.03.17 |
3. 연락처 추가 페이지, react-router-dom (0) | 2024.03.15 |
2. 연락처 목록 페이지, Axios (0) | 2024.03.14 |