首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法提供静态文件

无法提供静态文件
EN

Stack Overflow用户
提问于 2020-09-20 03:24:31
回答 1查看 416关注 0票数 1

由于任务是分发图片-我遵循下面的指南:

https://actix.rs/docs/static-files/

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

然后,我编写以下代码:

(只关注带有注释的行(只有两行):// Taken from the guide)

代码语言:javascript
复制
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

代码语言:javascript
复制
[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)而不得到这种错误,还需要写什么(以及确切地写在哪里)?

EN

回答 1

Stack Overflow用户

发布于 2020-09-20 06:12:11

问题解决了:

代码语言:javascript
复制
.service(Files::new("/static", std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("static")))

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63972621

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档