Help in static directory using ServeDir

I am very new to rust and axum and still learning.
Please help, when I tried to access "localhost:3001/assets", it gave 404 error.

My "assets" folder is located at /src/assets.

[package]
name = "axum_learning,"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.7.5"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.117"
tokio = { version = "1.37.0", features = ["full"] }
tower-http = { version = "0.5.2", features = ["fs"] }
#![allow(unused)] 

mod error;
pub use crate::error::{Result, Error};

use axum::{http::StatusCode, routing::get_service, Router};
use serde::{Deserialize, Serialize};
use tower_http::services::ServeDir;

#[tokio::main]
async fn main() {
    let static_route = Router::new().nest_service("/assets", get_service(ServeDir::new("./assets")));
    let api_v1 = Router::new(); // Todo()

    let app = Router::new()
    .merge(static_route)
    .nest("/v1", api_v1)
    .fallback(api_not_found_route());

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3001").await.expect("Failed to bind TCP Listener.");
    println!();
    println!("[INFO] Server is listening on {}.", listener.local_addr().unwrap());
    println!();
    axum::serve(listener, app).await.expect("axum::serve failed.");
}

fn api_not_found_route() -> (StatusCode, &'static str) {
    (StatusCode::NOT_FOUND, "ROUTE API NOT FOUND")
}

What response do you expect it to give you on this route? Server can't send the whole directory at once, after all.

I am expecting a list of files in the directory.

So according to your response, ServeDir can't do this.

What if I try to access "localhost:3001/assets/test.txt", will it show the content of the text file?

Thank you for your help.

Actually, it has this method, which allows you to make it do this behavior manually. Otherwise, it seems to be explicitly not done, yes.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.