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',
		}),
相关推荐
不好听61322 分钟前
React 父子组件通信:从 Todo 应用理解单向数据流
前端·react.js
_lucas30 分钟前
做了一个glsl在线调试工具
前端·javascript·three.js
早点睡啊Y2 小时前
深入学LangChain官方文档(二十二):Frontend 高级形态——Headless Tools、Time Travel 与 Generative UI
ui·langchain·状态模式
不好听6139 小时前
从一行 JSX 到屏幕像素:前端开发者必须懂的浏览器渲染管线
前端
恒拓高科WorkPlus9 小时前
企业级内网即时通讯建设模型:BeeWorks内网IM四层架构
前端
前端小李子10 小时前
前端环境变量裸奔?我用 EnvShield 给它穿了件防弹衣
前端
youtootech10 小时前
HarmonyOS《柚兔学伴》项目实战25-我的页面、Web 嵌入与项目总结
前端·华为·harmonyos
小林ixn10 小时前
从零到一理解 React 父子组件通信:手写一个 Todo 应用带你彻底搞懂单向数据流
前端·javascript·react.js
醇氧12 小时前
CountDownLatch / CyclicBarrier / Semaphore 面试高频问答清单
前端·面试·职场和发展