无法提供静态文件

时间:2020-09-19 19:24:30

标签: rust actix-web

由于任务是分发图片-我遵循下一个指南:
https://actix.rs/docs/static-files/

例如,我在项目中创建了一个目录(static),并向其中上传了1张图片:

введите сюда описание изображения

然后我编写以下代码:
(仅注意带有注释的行(只有两行):// Taken from the guide

use actix_cors::Cors;
use actix_web::{http, web, get, post, App, HttpResponse, HttpServer, Result};
use serde::{Deserialize, Serialize};
use actix_files::Files;  // Taken from the guide

#[derive(Serialize, Deserialize)]
struct MyObj {
    name: String,
}

#[derive(Serialize, Deserialize, Clone)]
struct MyParams {
    foo: Option<String>,
}

#[derive(Serialize, Deserialize)]
struct MyResponseObj {
    name: String,
    params: MyParams,
}

#[get("/{name}")]
async fn index_get(path: web::Path<MyObj>, params: web::Query<MyParams>) -> Result<HttpResponse> {

    Ok(HttpResponse::Ok().json(MyResponseObj {
        name: path.name.to_string(),
        params: params.clone(),
    }))
}

#[post("/{name}")]
async fn index_post(path: web::Path<MyObj>, params: web::Json<MyParams>) -> Result<HttpResponse> {

    hello().await;
    println!("{:?}", params.foo);
    println!("{:?}", path.name);

    Ok(HttpResponse::Ok().json(MyResponseObj {
        name: path.name.to_string(),
        params: params.clone(),
    }))
}


#[actix_rt::main]
async fn main() -> std::io::Result<()> {

    HttpServer::new(|| App::new()
        .wrap(
            Cors::new() // <- Construct CORS middleware builder
              .allowed_origin("http://localhost:3000")
              .allowed_methods(vec!["GET", "POST"])
              .allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
              .allowed_header(http::header::CONTENT_TYPE)
              .max_age(3600)
              .finish())
        .service(Files::new("/static", ".")) // Taken from the guide
        .service(index_get)
        .service(index_post)

    )
        .bind("127.0.0.1:8088")?
        .run()
        .await
}



Cargo.toml

[package]
name = "hello_world"
version = "0.1.0"
authors = ["Mike_Kharkov <yamaradg@gmail.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
actix-web = "3.0.1"
actix-rt = "1.1.1"
actix-cors = "0.3.0"
actix-files = "0.3.0"
postgres = "0.17.5"
serde = { version = "1.0.116", features = ["derive"] }
serde_json = "1.0"
json = "0.12"
tokio-postgres = "0.5.5"
tokio = "0.2.22"
env_logger = "0.7.1"


问题:
还需要写些什么(以及确切地写在什么地方),以便可以引用上面的图片(例如,从localhost),而不会出现这种错误?

введите сюда описание изображения

1 个答案:

答案 0 :(得分:1)

问题已解决:

.service(Files::new("/static", std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("static")))

enter image description here