Rust如何编制前端路由

目的:根据前端build文件夹下的目录结构,生成路由,将前端html文件返回。

rust 复制代码
/// 设置 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、要用客户端接管所有的路由处理

ts 复制代码
# svelte.config.js
		adapter: adapter({
			fallback: 'index.html',
		}),
相关推荐
Birdy_x1 分钟前
接口自动化项目实战(1):requests请求封装
开发语言·前端·python
天天向上10241 小时前
vue el-table实现拖拽排序
前端·javascript·vue.js
柳杉2 小时前
Three.js × Blender:从建模到 Web 3D 的完整工作流深度解析
前端·javascript·数据可视化
reembarkation3 小时前
vue3中使用howler播放音频列表
前端·vue.js·音视频
手握风云-3 小时前
基于 Java 的网页聊天室(三)
服务器·前端·数据库
weixin199701080164 小时前
《识货商品详情页前端性能优化实战》
前端·性能优化
Forever7_4 小时前
重磅!Vue3 手势工具正式发布!免费使用!
前端·前端框架·前端工程化
用户806138166594 小时前
发布为一个 npm 包
前端·javascript
树上有只程序猿4 小时前
低代码何时能出个“秦始皇”一统天下?我是真学不动啦!
前端·后端·低代码
TT_哲哲4 小时前
小程序双模式(文件 / 照片)上传组件封装与解析
前端·javascript