【问题标题】:Serving static files with actix-web 2.0使用 actix-web 2.0 提供静态文件
【发布时间】:2020-08-30 02:55:03
【问题描述】:

我正在为 rust 的 actix-web 2.0 框架而苦苦挣扎。我希望我的 rust 服务器为我的 index.html 文件提供服务,但大多数可用的帮助都是旧版本的,因此在新版本中发生了很多变化。我尝试了以下代码,但它不适用于 actix-web 2.0。请在 actix-web 2.0 中提出一些可行的解决方案。抱歉,我对 rust 很陌生。

use actix_files::NamedFile;
use actix_web::{HttpRequest, Result};
async fn index(req: HttpRequest) -> Result<NamedFile> {
   Ok(NamedFile::open(path_to_file)?)
}

Edit1:我遇到类型不匹配错误,但使用 cmets 中回答的 pathBuf 救了我。

Edit2:通过尝试答案中给出的代码,我可以提供单个 html 文件,但无法加载链接的 javascript 文件。我尝试了https://actix.rs/docs/static-files/ 中建议的以下方法来服务目录

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    dotenv::dotenv().ok();
    std::env::set_var("RUST_LOG", "actix_web=debug");
    let database_url = std::env::var("DATABASE_URL").expect("set DATABASE_URL");

    // create db connection pool
    let manager = ConnectionManager::<PgConnection>::new(database_url);
    let pool: Pool = r2d2::Pool::builder()
        .build(manager)
        .expect("Failed to create pool.");
    
    //Serving the Registration and sign-in page
    async fn index(_req: HttpRequest) -> Result<NamedFile> {
        let path: PathBuf = "./static/index.html".parse().unwrap();
        Ok(NamedFile::open(path)?)
    }

    // Start http server
    HttpServer::new(move || {
        App::new()
            .data(pool.clone())
            .service(fs::Files::new("/static", ".").show_files_listing())
            .route("/", web::get().to(index))
            .route("/users", web::get().to(handler::get_users))
            .route("/users/{id}", web::get().to(handler::get_user_by_id))
            .route("/users", web::post().to(handler::add_user))
            .route("/users/{id}", web::delete().to(handler::delete_user))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

以上是我的主要方法。在浏览器控制台中,我仍然收到无法加载 Registration.js 资源的错误。以下是我的文件夹结构:

-migrations
-src
  -main.rs
  -handler.rs
  -errors.rs
  -models.rs
  -schema.rs
-static
 -index.html
 -Registration.js
-target
Cargo.toml
.env
Cargo.lock
diesel.toml

我已经用 db 集成构建了后端,并且通过 curl 命令检查它工作正常,现在我正在尝试构建前端并作为尝试提供静态文件的第一步。

Edit3:也帮助我解决此问题的示例是https://github.com/actix/examples/tree/master/static_index

【问题讨论】:

  • 尝试现有代码时会发生什么?它在什么方面没有做你想做的事?
  • @harmic 我已经编辑了我的问题。看看你能不能找到什么。
  • fs::Files::new 的第二个参数是您要服务的目录。 "." 将是当前目录 - 这将是您运行的任何目录,而不是“静态”目录。尝试将完整路径放入静态目录。
  • @yes 感谢您的解释。我发现了。我还在我的问题中提供了一个很好的用法示例。

标签: rust static-files rust-actix actix-web


【解决方案1】:

由于描述不详细,我不确定您遇到了什么问题,但是,我运行了默认示例并且正在运行。

use actix_files::NamedFile;
use actix_web::{HttpRequest, Result};
use std::path::PathBuf;

/// https://actix.rs/docs/static-files/
async fn index(_req: HttpRequest) -> Result<NamedFile> {
    let path: PathBuf = "./files/index.html".parse().unwrap();
    Ok(NamedFile::open(path)?)
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{web, App, HttpServer};

    HttpServer::new(|| App::new().route("/", web::get().to(index)))
        .bind("127.0.0.1:8088")?
        .run()
        .await
}

项目结构

- files/index.html
- src/index.rs
- cargo.toml

依赖

[dependencies]
actix-web = "2.0.0"
actix-files = "0.2.2"
actix-rt = "1.1.1"

希望这对你有用

【讨论】:

  • 感谢它对我有用。缺少 pathBuf,它救了我。
  • 你能回答另一个问题吗?我的 html 文件正在服务,但似乎没有提供链接的 JS。你有什么建议
  • 在这里查看actix.rs/docs/static-files 目录部分,以便您可以提供目录中的所有内容,包括 CSS、JS 或您那里的任何文件
  • 我仍然无法加载其他资源。我已经编辑了我的帖子。请看看你是否能发现我做错了什么?
【解决方案2】:

如果您想真正将资源嵌入到可执行文件中,您可以使用https://crates.io/crates/actix-web-static-files

它使用build.rs 来准备资源,之后你可以只拥有一个没有依赖关系的可执行文件。

此外,它还支持基于 npm 的开箱即用构建。

基本上我是这个箱子的作者。 actix-web 有 2.x 和 3.x 版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 2013-10-17
    • 2011-01-27
    • 2015-03-04
    • 2012-08-20
    相关资源
    最近更新 更多