我正在与 Rust 的 actix-web 2.0 框架作斗争。我希望我的 rust 服务器能够为我的 index.html 文件提供服务,但大多数可用的帮助都是旧版本的,因此新版本中发生了很多变化。我尝试了以下代码,但它不适用于 actix-web 2.0。请在 actix-web 2.0 中提出一些可行的解决方案。
use actix_files::NamedFile;
use actix_web::{HttpRequest, Result};
async fn index(req: HttpRequest) -> Result<NamedFile> {
Ok(NamedFile::open(path_to_file)?)
}
通过尝试答案中给出的代码,我可以提供单个 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
我已经使用数据库集成构建了后端,并且通过curl 命令检查它工作正常,现在我正在尝试构建前端并作为尝试提供静态文件的第一步。