通常,React版本只是像nginx这样的Web服务器中的静态文件提供,但是我想使用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文件之类的功能,我宁愿不为每个文件添加特定的路由,有人能以更好的方式解决此问题吗?
请在此处查看项目代码
/<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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句