Quickstarters
리믹스 프론트엔드를 구축하고 백엔드에 연결하는 방법은 무엇인가요?
21 분
이 튜토리얼에서는 remix를 사용하여 할 일 목록 애플리케이션을 구축하고 이를 back4app의 관리형 백엔드 서비스에 연결합니다 이 단계별 가이드는 필수 crud 작업을 마스터하고 remix를 사용하여 동적 사용자 인터페이스를 설계하는 데 도움이 되도록 설계되었습니다 풀스택 애플리케이션을 구축하려면 프론트엔드와 백엔드를 모두 설정해야 합니다 back4app을 사용하면 확장 가능한 백엔드 서비스(baas)를 활용할 수 있으므로 서버 구성에 얽매이지 않고 매력적인 사용자 경험을 만드는 데 집중할 수 있습니다 back4app은 원활한 통합을 위한 준비된 데이터베이스, 인증, 클라우드 기능 및 sdk를 제공합니다 이러한 기능을 통해 remix 애플리케이션을 신속하게 프로토타입하고 구축하며 배포할 수 있습니다 주요 내용 이 튜토리얼을 따르면 다음을 수행할 수 있습니다 업계 표준 도구를 사용하여 현대적인 remix 프로젝트를 초기화합니다 parse sdk를 사용하여 remix 프론트엔드를 back4app 백엔드에 연결합니다 crud 작업을 구현하여 할 일 목록 을 관리합니다 remix 앱을 컨테이너화하고 back4app 웹 배포를 통해 배포합니다 전제 조건 시작하기 전에 다음 사항을 확인하세요 node js 및 npm 이 시스템에 설치되어 있습니다 터미널에서 node v 및 npm v 를 실행하여 확인하세요 기본 remix 지식 , 라우팅, 로더 및 액션을 포함합니다 remix는 react를 기반으로 하므로 react 개념에 대한 친숙함이 도움이 됩니다 back4app 계정 을 통해 백엔드 서비스를 구성하고 관리합니다 아직 계정이 없다면 back4app https //www back4app com/ 에서 가입하세요 이 도구들을 갖추면 remix 애플리케이션을 만들고 강력한 백엔드와 통합할 준비가 완료됩니다 프로젝트 설정 먼저, 로컬 개발 환경을 설정하고 remix 프로젝트를 초기화합니다 이렇게 하면 애플리케이션을 위한 깨끗하고 효율적인 기반을 확보할 수 있습니다 다음 명령어를 사용하여 remix 프로젝트를 설치합니다 원하는 프로젝트 이름으로 todo app 을(를) 교체하세요 npx create remix\@latest todo app 새 프로젝트 디렉토리로 이동합니다 cd todo app 개발 서버를 실행하여 모든 것이 제대로 작동하는지 확인합니다 npm run dev 터미널에 제공된 url을 열어 remix 앱이 성공적으로 실행되고 있는지 확인합니다 back4app에서 todo 백엔드 설정하기 back4app은 parse로 구동되는 강력한 관리형 백엔드를 제공합니다 작업을 위한 데이터 모델을 생성하게 되며, 이는 할 일 목록 애플리케이션의 중추 역할을 하게 됩니다 백엔드 애플리케이션 만들기 당신의 back4app 대시보드 https //www back4app com/ 에 로그인하고 "새 앱 만들기" 애플리케이션의 이름을 지정하세요 (예 todoremixapp ) 그리고 백엔드 유형으로 nodejs/parse 를 선택하세요 "데이터베이스" > "브라우저" 섹션에서 "클래스 만들기" 를 클릭하고 "사용자 정의" 를 선택하세요 클래스를 task 로 이름 짓고 클래스 수준 권한을 설정하여 공개 읽기 및 쓰기를 허용하세요 (이 설정은 나중에 수정할 수 있습니다) 다음 필드를 task 클래스에 추가하세요 title (문자열) – 작업의 이름 description (문자열) – 작업에 대한 세부정보 completed (부울) – 작업이 완료되었는지 여부를 나타냅니다 duedate (날짜) – 작업의 마감일 "저장" 을 클릭하여 스키마를 완료하세요 remix와 back4app 통합하기 remix 앱을 back4app과 연결하기 위해 parse javascript sdk를 사용할 것입니다 다음 명령어를 실행하여 sdk를 설치하세요 npm install parse 다음으로, remix 애플리케이션 내에서 parse를 구성합니다 app/root tsx 파일을 열고 상단에 다음 초기화 코드를 추가하세요 'your application id' 및 'your javascript key' 를 back4app 대시보드의 자격 증명으로 교체하세요 ( 앱 설정 > 보안 및 키 ) // app/root tsx import parse from "parse"; import react from "react"; const parse app id = 'your application id'; const parse js key = 'your javascript key'; const parse server url = 'https //parseapi back4app com/'; parse initialize(parse app id, parse js key); (parse as any) serverurl = parse server url; 로더 함수가 실행될 때 parse가 완전히 초기화되도록 하세요, 특히 서버 측에서 이 코드를 layout 함수에 추가하세요 root tsx 파일에 // app/root tsx export function layout({ children } { children react reactnode }) { react useeffect(() => { if (typeof window !== 'undefined') { parse initialize(parse app id, parse js key); (parse as any) serverurl = "https //parseapi back4app com/"; } }, \[]); // rest of the layout function } 이 설정은 당신의 remix 경로와 액션이 back4app 백엔드와 원활하게 상호작용할 수 있게 해줍니다 remix로 프론트엔드 구축하기 백엔드가 구성되었으므로 이제 remix를 사용하여 할 일 목록 인터페이스를 구축할 것입니다 여기에는 데이터 가져오기 및 변형을 처리하기 위한 경로, 로더 및 액션을 만드는 것이 포함됩니다 경로 구조화하기 remix에서는 모든 경로가 app/routes 디렉토리 아래의 파일에 해당합니다 app/routes/ index tsx 를 열고 페이지의 구조와 데이터 작업을 정의하기 위해 다음 코드를 추가하세요 // app/routes/ index tsx import { json, redirect } from "@remix run/node"; import { useloaderdata, form } from "@remix run/react"; import as parse from "parse"; export const loader = async () => { if (typeof window === "undefined") { try { const response = await fetch( "https //parseapi back4app com/classes/task", { headers { "x parse application id" "your application id", "x parse javascript key" "your javascript key", }, } ); const data = await response json(); return json({ tasks data results map((task) => ({ id task objectid, task })), }); } catch (error) { console error("error fetching tasks ", error); return json({ tasks \[] }); } } else { try { const task = parse object extend("task"); const query = new parse query(task); const results = await query find(); const tasks = results map((task) => ({ id task id, task tojson() })); return json({ tasks }); } catch (error) { console error("error fetching tasks ", error); return json({ tasks \[] }); } } }; export const action = async ({ request }) => { const formdata = await request formdata(); const actiontype = formdata get("actiontype"); // parse server details const parseserverurl = "https //parseapi back4app com"; const headers = { "x parse application id" "your application id", "x parse javascript key" "your javascript key", "content type" "application/json", }; try { if (actiontype === "add") { const title = formdata get("title"); const description = formdata get("description"); // create task using rest api const response = await fetch(`${parseserverurl}/classes/task`, { method "post", headers, body json stringify({ title, description, completed false, }), }); if (!response ok) { throw new error(`failed to add task ${response status}`); } } else if (actiontype === "toggle") { const id = formdata get("id"); // first get the current task to check its completed status const getresponse = await fetch(`${parseserverurl}/classes/task/${id}`, { headers, }); if (!getresponse ok) { throw new error(`failed to get task ${getresponse status}`); } const task = await getresponse json(); const updateresponse = await fetch( `${parseserverurl}/classes/task/${id}`, { method "put", headers, body json stringify({ completed !task completed, }), } ); if (!updateresponse ok) { throw new error(`failed to update task ${updateresponse status}`); } } else if (actiontype === "delete") { const id = formdata get("id"); const deleteresponse = await fetch( `${parseserverurl}/classes/task/${id}`, { method "delete", headers, } ); if (!deleteresponse ok) { throw new error(`failed to delete task ${deleteresponse status}`); } } return redirect("/"); } catch (error) { console error("error processing action ", error); return json({ error error message }, { status 400 }); } }; export default function todoroute() { const { tasks } = useloaderdata(); return ( \<div classname="container"> \<h1>to do list\</h1> \<form method="post" classname="form"> \<input type="hidden" name="actiontype" value="add" /> \<input type="text" name="title" placeholder="task title" required /> \<input type="text" name="description" placeholder="description" required /> \<button type="submit">add task\</button> \</form> \<div classname="tasks"> {tasks length === 0 ? ( \<p>no tasks available\</p> ) ( tasks map(task => ( \<div key={task id} classname={`task item ${task completed ? "completed" ""}`}> \<h3>{task title}\</h3> \<p>{task description}\</p> \<form method="post"> \<input type="hidden" name="actiontype" value="toggle" /> \<input type="hidden" name="id" value={task id} /> \<button type="submit">{task completed ? "undo" "complete"}\</button> \</form> \<form method="post"> \<input type="hidden" name="actiontype" value="delete" /> \<input type="hidden" name="id" value={task id} /> \<button type="submit">delete\</button> \</form> \</div> )) )} \</div> \</div> ); } 이 경로는 remix의 로더와 액션을 사용하여 back4app에서 작업을 가져오고 작업 추가, 전환 및 삭제와 같은 사용자 상호작용을 처리합니다 리믹스 앱 스타일링 기본적인 애플리케이션의 모양과 느낌을 정의하기 위해 app/global css 에 css 파일을 생성하세요 / app/global css / container { max width 600px; margin 40px auto; padding 0 20px; text align center; font family sans serif; } container h1 { margin bottom 20px; } form { display flex; flex direction column; align items center; gap 10px; margin bottom 20px; } form input\[type="text"] { width 80%; max width 400px; padding 8px; font size 1rem; } form button { padding 8px 16px; cursor pointer; font size 1rem; border none; background color #eaeaea; transition background color 0 2s ease; } form button\ hover { background color #ccc; } tasks p { font size 1rem; } task item { display flex; flex direction column; align items center; gap 12px; border 1px solid #ccc; border radius 6px; padding 15px; margin 10px 0; background color #fafafa; text align center; transition background color 0 2s ease; } task item completed h3, task item completed p { text decoration line through; color #888; } task item h3 { margin 0; font size 1 1rem; } task item p { margin 0; font size 1rem; } task item button { padding 6px 12px; border none; background color #eaeaea; cursor pointer; font size 0 9rem; } task item button\ hover { background color #ccc; } @media (min width 600px) { task item { flex direction row; } } css 파일을 app/root tsx 에 추가하여 가져오세요 // app/root tsx import " /global css"; 이제 리믹스 앱은 back4app의 백엔드와 상호작용하는 기능적인 할 일 목록 인터페이스를 가지고 있습니다 back4app에서 리믹스 앱 컨테이너화 및 배포 back4app 웹 배포는 애플리케이션을 위한 컨테이너화된 환경을 제공합니다 리믹스 앱을 docker 컨테이너로 패키징하고 배포할 것입니다 생산을 위한 리믹스 구성 컨테이너화하기 전에 리믹스 앱을 생산 준비가 된 번들로 빌드하세요 npm run build 도커파일 만들기 다음 내용을 포함하여 프로젝트의 루트에 dockerfile 을(를) 만드세요 \# stage 1 build the remix app from node 18 alpine as builder workdir /app copy package json package lock json / run npm install copy run npm run build \# stage 2 serve the app using a lightweight node server from node 18 alpine workdir /app copy from=builder /app/build /build copy from=builder /app/package json / run npm install production expose 3000 cmd \["npm", "run", "start"] 이 dockerfile은 remix 프로젝트를 빌드하고 최소한의 node js 런타임을 사용하여 프로덕션을 위해 준비합니다 도커 컨테이너 빌드 및 테스트 로컬에서 도커 이미지를 빌드하세요 docker build t todo remix frontend 배포를 테스트하기 위해 컨테이너를 실행하세요 docker run p 8080 3000 todo remix frontend 브라우저에서 http //localhost 8080 를 방문하여 remix 앱이 올바르게 실행되고 있는지 확인하세요 back4app 웹 배포를 통한 배포 프로젝트를 github에 푸시하세요 git init git add git commit m "initial commit for back4app deployment" git branch m main git remote add origin \<your github repository url> git push u origin main 그런 다음, back4app 웹 배포 https //www back4app com/containers 에 로그인하고 다음 단계를 따르세요 "새 앱 만들기"를 클릭하고 프로젝트 이름을 지정하세요 "github 리포지토리"를 선택하고 back4app을 승인하세요 당신의 todo remix 리포지토리를 선택하세요 "dockerfile 배포"를 선택하고 빌드 설정을 확인하세요 "배포"를 클릭하여 빌드를 시작하세요 배포 후, back4app 대시보드를 통해 컨테이너를 모니터링하세요 로그를 보고, 빌드를 관리하고, 사용자 도메인을 구성할 수 있습니다 애플리케이션 테스트 및 디버깅 배포가 완료되면 애플리케이션이 예상대로 작동하는지 확인하세요 프론트엔드 백엔드 통합을 확인하는 방법은 다음과 같습니다 api 연결 브라우저의 개발자 콘솔(f12)을 열고 작업을 추가, 전환 또는 삭제할 때 네트워크 요청을 확인하세요 데이터 지속성 ui를 통해 작업을 추가하고 페이지를 새로 고쳐서 저장되었는지 확인하세요 back4app 데이터베이스 브라우저에서 task 클래스를 확인하세요 crud 작업 완료 상태를 전환하고 작업을 삭제해 보세요 문제가 발생하면 콘솔과 api 로그를 검사하세요 엣지 케이스 처리 유효성 검사가 효과적인지 확인하기 위해 빈 입력을 제출해 보세요 모범 사례 및 최적화 팁 보안을 강화하고 성능 및 확장성을 높이기 위해 다음 권장 사항을 따르세요 api 호출 최적화 배치 요청을 사용하고 쿼리에서 필요한 필드만 선택하세요 환경 변수 민감한 키(애플리케이션 id 및 javascript 키)를 env 파일에 저장하고 안전하게 참조하세요 액세스 제어 인증된 사용자에게 데이터 수정을 제한하기 위해 동적 acl을 구현하세요 클라우드 코드 성능과 보안을 개선하기 위해 복잡한 로직을 back4app 클라우드 코드로 오프로드하세요 결론 당신은 성공적으로 remix로 전체 스택 할 일 목록 애플리케이션을 구축하고 back4app 백엔드에 연결했습니다 이 튜토리얼은 remix 프로젝트 초기화, 백엔드 상호작용을 위한 관리 서비스 통합, 배포를 위한 애플리케이션 컨테이너화 과정을 안내했습니다 이제 앱이 라이브 상태이므로 고급 사용자 관리, 실시간 업데이트 또는 타사 통합으로 기능을 확장하는 것을 고려하세요 추가 안내를 원하시면 back4app 문서 https //www back4app com/docs 및 remix 리소스를 탐색하세요