我正在为rust的actix-Web2.0框架而挣扎。我希望我的rust服务器为我的index.html文件提供服务,但大多数可用的帮助都是旧版本的,因此在新版本中有很多变化。我尝试了下面的代码,但它不适用于actix-web2.0。请在actix-Web2.0中推荐一些可行的解决方案。很抱歉我犯了一些错误,因为我是个生锈新手。
use actix_files::NamedFile;
use actix_web::{HttpRequest, Result};
async fn index(req: HttpRequest) -> Result<NamedFile> {
Ok(NamedFile::open(path_to_file)?)
}Edit1:我遇到了类型不匹配错误,但使用注释中回答的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我已经构建了与数据库集成的后端,它工作得很好,正如curl命令所检查的那样,现在我正在尝试构建前端,并作为第一步尝试服务静态文件。
Edit3:https://github.com/actix/examples/tree/master/static_index这个例子也帮助我解决了这个问题
发布于 2020-08-30 18:19:31
我不确定你面临的是什么问题,因为描述并不详细,但是,我运行了默认的示例,并且正在工作。
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"希望这对你有用
发布于 2020-10-28 21:41:05
如果你想真正将资源嵌入到可执行文件中,你可以使用https://crates.io/crates/actix-web-static-files。
它使用build.rs来准备资源,以后您可以只有一个没有依赖关系的可执行文件。
此外,它还支持开箱即用的基于npm的构建。
基本上我是这个板条箱的作者。actix-web的2.x和3.x版本都有相应的版本。
https://stackoverflow.com/questions/63653540
复制相似问题