目的:根据前端build文件夹下的目录结构,生成路由,将前端html文件返回。
/// 设置 HTML 文件路由
pub fn route(cfg: &mut web::ServiceConfig) {if Path::new("client/build/index.html").exists() {let index_content = match fs::read_to_string("client/build/index.html") {Ok(content) => content,Err(e) => {log::error!("无法读取 index.html: {}", e);return;}};let index_content = web::Data::new(index_content);cfg.service(web::resource("/user/authorize/").app_data(index_content.clone()).route(web::get().to(serve_index)),);cfg.service(web::resource("/condition-monitoring/parameter-display/parameter-list-display/create-list",).app_data(index_content.clone()).route(web::get().to(serve_index)),);for entry in WalkDir::new("client/build") {if let Ok(entry) = entry {if entry.path().extension().map_or(false, |ext| ext == "html") {if let Ok(rel_path) = entry.path().strip_prefix("client/build") {let route_path = rel_path.with_extension("").to_string_lossy().replace("\\", "/");let route_path = if route_path.ends_with("index") {route_path.trim_end_matches("index").to_string()} else {route_path.to_string()};cfg.service(web::resource(format!("/{}", route_path)).app_data(index_content.clone()).route(web::get().to(serve_index)),);}}}}} else {log::error!("index.html 未找到");}
}
在使用 svelte
开发的时候遇到以下问题:
1、+layout.ts
设置 trailingSlash = 'always'
之后,无法索引到正确路径;
解决方案:trailingSlash = 'never'
2、要用客户端接管所有的路由处理
# svelte.config.jsadapter: adapter({fallback: 'index.html',}),