ABOUT ME

-

  • Rust: actix-rs + React.js
    컴퓨터/Rust 2023. 6. 2. 19:53
    728x90
    반응형

    소개: actix-rs (백엔드)에서 React.js (프론트엔드)를 간단하게 사용하는 방법이다.

     

    우선 프론트엔드 폴더에서 프로젝트를 빌드하고

    bash
    yarn build

     

    백엔드를 아래처럼 수정한다.

     

    1. 터미널에서

    bash
    cargo add actix-files

     

    2. main.rs

    actix_files로 파일 임베딩을 하는 법이다.

    현재 백엔드 프로젝트 폴더가 A/ 라고 할 때 프론트엔드 빌드 결과물이 A/google-clone/build 에 있고 그 안에 index.html을 사용한다.

    rust
    ... use actix_files as fs; ... #[actix_web::main] async fn main() -> std::io::Result<()> { ... // Start the HTTP server HttpServer::new(move || { App::new() ... // 아래 라인 .service(fs::Files::new("/", "./google-clone/build").index_file("index.html")) }) .keep_alive(Duration::from_secs(600)) .bind(server_address)? .run() // Start the HTTP server .await }

     

    이렇게 하면 프론트엔드에서 백엔드 부분 fetch할 때 서버 주소 하드코딩 안하고

    아래처럼 actix-rs에서 만든 /rust_call이라는 POST 함수에 바로 부를 수 있다.

    javascript
    useEffect(() => { const fetchData = async () => { setLoading(true); fetch("/rust_call", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ k: k, }), }) .then(response => response.json()) .then(result => { setData(result); setLoading(false); }) .catch(error => { dispatch({ type: actionTypes.SET_ERROR, error: error.message, }); console.error("Error:", error); setLoading(false); }); };
    728x90

    댓글