핫트레이딩

AI 기반 자동 프로그래밍 시스템 – 전체 설계도 (6) 본문

IT 정보/인공지능 Ai

AI 기반 자동 프로그래밍 시스템 – 전체 설계도 (6)

HOTT 2025. 8. 26. 19:04

React(프론트엔드) → FastAPI(백엔드) 연결 방법을 설명드리겠습니다.
이 단계가 끝나면 **"개발자 노트를 UI에서 입력 → 서버에 저장"**이 완전히 동작합니다.


1. 현재 상태

  • 프론트엔드: React UI (App.js) 완료
  • 백엔드: FastAPI (main.py) 완료

2. 목표

  1. React에서 입력값을 FastAPI로 POST 요청
  2. 저장된 노트 목록을 React에서 가져와 화면에 표시(GET 요청)

3. FastAPI CORS 설정 (필수)

React와 FastAPI가 서로 다른 포트(3000, 8000)에서 실행되므로 CORS 설정 필요

backend/main.py에 추가:

python
from fastapi.middleware.cors import CORSMiddleware

# CORS 설정 (React localhost:3000 허용)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 개발 단계에서는 * (모두 허용)
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
 

4. React에서 API 호출 코드 추가

frontend/src/App.js 수정:

javascript
import React, { useState, useEffect } from "react";

export default function App() {
  const [projectName, setProjectName] = useState("");
  const [mustHave, setMustHave] = useState("");
  const [mustNotHave, setMustNotHave] = useState("");
  const [reviewRequired, setReviewRequired] = useState("");
  const [notes, setNotes] = useState([]); // 저장된 노트 목록

  // 서버에서 노트 목록 가져오기 (GET)
  const fetchNotes = async () => {
    try {
      const res = await fetch("http://127.0.0.1:8000/notes");
      const data = await res.json();
      setNotes(data);
    } catch (err) {
      console.error("노트 목록 가져오기 실패:", err);
    }
  };

  useEffect(() => {
    fetchNotes();
  }, []);

  // 노트 저장 (POST)
  const handleSave = async () => {
    const note = {
      projectName,
      mustHave: mustHave.split(",").map(item => item.trim()),
      mustNotHave: mustNotHave.split(",").map(item => item.trim()),
      reviewRequired: reviewRequired.split(",").map(item => item.trim())
    };

    try {
      const res = await fetch("http://127.0.0.1:8000/notes", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(note)
      });

      if (res.ok) {
        alert("노트가 저장되었습니다!");
        fetchNotes(); // 목록 새로고침
      } else {
        alert("저장 실패!");
      }
    } catch (err) {
      console.error("저장 오류:", err);
    }
  };

  return (
    <div className="min-h-screen bg-gray-100 flex items-center justify-center">
      <div className="bg-white shadow-lg rounded-2xl p-6 w-full max-w-md">
        <h1 className="text-2xl font-bold mb-4">개발자 노트 작성</h1>

        {/* 입력 필드 */}
        <label className="block mb-2 font-semibold">프로젝트 이름</label>
        <input
          type="text"
          value={projectName}
          onChange={(e) => setProjectName(e.target.value)}
          className="border rounded-lg w-full p-2 mb-4"
          placeholder="예: shrimp_farm_manager"
        />

        <label className="block mb-2 font-semibold">필수 기능</label>
        <input
          type="text"
          value={mustHave}
          onChange={(e) => setMustHave(e.target.value)}
          className="border rounded-lg w-full p-2 mb-4"
          placeholder="예: 로그인, 수조 온도 모니터링"
        />

        <label className="block mb-2 font-semibold">제외 기능</label>
        <input
          type="text"
          value={mustNotHave}
          onChange={(e) => setMustNotHave(e.target.value)}
          className="border rounded-lg w-full p-2 mb-4"
          placeholder="예: 외부 데이터 전송"
        />

        <label className="block mb-2 font-semibold">승인 필요한 변경사항</label>
        <input
          type="text"
          value={reviewRequired}
          onChange={(e) => setReviewRequired(e.target.value)}
          className="border rounded-lg w-full p-2 mb-4"
          placeholder="예: DB 스키마 변경"
        />

        {/* 버튼 */}
        <div className="flex justify-between mt-4">
          <button
            onClick={handleSave}
            className="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600"
          >
            저장하기
          </button>
        </div>

        {/* 저장된 노트 목록 */}
        <h2 className="text-xl font-bold mt-6 mb-2">저장된 노트 목록</h2>
        <ul className="list-disc pl-5">
          {notes.map((n, i) => (
            <li key={i} className="text-sm mb-1">
              <strong>{n.projectName}</strong> | 필수: {n.mustHave.join(", ")}
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}
 

5. 실행 순서

  1. 백엔드 실행
    cd backend
    uvicorn main:app --reload
  2. 프론트엔드 실행
    cd frontend
    npm start
  3. 브라우저에서 http://localhost:3000 접속
    • 프로젝트명 입력 → 저장 → 목록에 추가되는 것 확인

6. 이 단계가 끝나면

  • 프론트에서 작성한 노트가 백엔드에 저장되고, UI에 실시간으로 반영됩니다.
  • 이제 AI를 붙이면 → "노트 기반 코드 생성"이 가능해집니다.

다음 단계 제안:

  1. AI 연동 단계 (OpenAI API 연결, 노트를 기반으로 코드 생성)
  2. Git 자동화 단계 (코드 수정 → Git Commit & Push)

 

반응형