有没有一种干净的方法可以从Rust Rocket后端服务React构建

时间:2020-09-16 09:14:42

标签: reactjs rust rust-rocket

通常,React版本只是作为Web服务器(如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

1 个答案:

答案 0 :(得分:2)

/<path..>模式是递归的,您不需要包括子文件夹。只需在/上为您的整个版本提供服务,即可正常使用。

唯一需要担心的是从/之类的模棱两可的页面路径进行重定向。

#![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();
}
相关问题