【问题标题】:Is there a clean way to serve React builds from a Rust Rocket backend有没有一种干净的方法可以从 Rust Rocket 后端服务 React 构建
【发布时间】:2020-09-16 09:14:42
【问题描述】:

通常 React 构建只是作为来自 nginx 等网络服务器的静态文件提供,但我想使用来自 React 构建的 Rust Rocket 提供前端静态文件,我正在努力寻找一种好的方法,这里是我设置的路线

#[get("/")]
 fn index() -> io::Result<NamedFile> {
NamedFile::open("build/index.html")
}

#[get("/<file..>", rank = 2)]
fn build_dir(file: PathBuf) -> Option<NamedFile> {
    NamedFile::open(Path::new("build/").join(file)).ok()
}

#[get("/static/<file..>")]
fn static_dir(file: PathBuf) -> Option<NamedFile> {
    NamedFile::open(Path::new("build/static/").join(file)).ok()
}

fn rocket() -> rocket::Rocket {
    rocket::ignite()
        .mount("/", routes![index, build_dir])
        .mount("/static", routes![static_dir])
}

这可行,但它不提供 favicons 或 manifest.json 文件之类的东西,我不想为每个文件添加特定的路由,有没有人以更好的方式解决了这个问题?

请看项目代码here

【问题讨论】:

    标签: reactjs rust rust-rocket


    【解决方案1】:

    /&lt;path..&gt; 模式是递归的,你不需要包含子文件夹。只需在 / 上提供您的整个构建,它就会按预期工作。

    唯一需要担心的是从 / 等不明确的页面路径重定向。

    #![feature(proc_macro_hygiene, decl_macro)]
    
    use std::{io, path::{Path, PathBuf}};
    
    use rocket::{get, routes, response::{NamedFile, Redirect}};
    
    #[get("/")]
    fn index() -> Redirect {
        Redirect::permanent("/index.html")
    }
    
    #[get("/<file..>")]
    fn build_dir(file: PathBuf) -> io::Result<NamedFile> {
        NamedFile::open(Path::new("build/").join(file))
    }
    
    fn rocket() -> rocket::Rocket {
        rocket::ignite()
            .mount("/", routes![index, build_dir])
    }
    
    fn main() {
        rocket().launch();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-30
      • 1970-01-01
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      • 2018-06-30
      • 2015-03-08
      相关资源
      最近更新 更多