< 返回版块

C-Jeril 发表于 2024-01-19 09:44

不确定现在到底rust+axum+deisel+postgresql的背景到底现在要解决cors问题应该用哪个依赖项了 有说axum-cors,uctower_http::cors::CorsLayer;,axum_util::cors::CorsLayer;但是最终代码层面都会报错。

[dependencies]
axum = "^0.7.4"
tokio = { version = "^1", features = ["full"] }
diesel = { version = "^2.1.0", features = ["postgres", "r2d2", "chrono"] }
chrono = { version = "^0.4.31", features = ["serde"] }
r2d2 = "0.8.10"
serde = { version = "^1.0", features = ["derive"] }
serde_json = "1.0"
dotenv = "0.15.0"
postgres = "0.19.2"
http = "0.2"
diesel-async = "0.4.1"
r2d2_postgres = "0.18.1"
log = "0.4.20"
env_logger = "0.10.1"
tower = "0.4.13"
tower-http = "0.5.1"
hyper = "1.1.0"
server = "0.1.0"
axum-util = "0.2.2"
tracing = "0.1.40"
axum-extra = "0.9.2"


// src/routes.rs
use axum::{
    http::StatusCode,
    response::{IntoResponse, Json},
    routing::{get, post, put, delete, options},
    Extension,
    Router,
};

use crate::{service::draw_random_card, DbPool};
use axum_util::cors::CorsLayer;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct ErrorResponse {
    error_message: String,
}

impl IntoResponse for ErrorResponse {
    fn into_response(self) -> axum::response::Response {
        let body = Json(self).into_response();
        (StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
    }
}

#[derive(Serialize, Debug)]
pub struct CardResponse {
    id: i32,
    name: String,
    description: Option<String>,
    image_url: Option<String>,
}

pub async fn draw_card_handler(
    Extension(pool): Extension<DbPool>,
) -> Result<Json<CardResponse>, (StatusCode, String)> {
    match draw_random_card(&pool).await {
        Ok(card) => {
            let response = CardResponse {
                id: card.id,
                name: card.name,
                description: card.description,
                image_url: card.image_url,
            };
            Ok(Json(response))
        }
        Err(e) => Err((e.0, format!("内部服务器错误: {}", e.1))),
    }
}

pub fn app_router(pool: DbPool) -> Router {
    let cors = CorsLayer::new()
        .allow_origin("http://localhost:5173")
        .allow_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"])
        .allow_headers(vec!["Content-Type", "Authorization"])
        .max_age(3600);

    Router::new()
        .layer(cors)
        .route("/api/cards/draw", get(draw_card_handler))
        .route("/api/cards/draw", options(options_handler))
        .layer(Extension(pool))
}

async fn options_handler() -> impl IntoResponse {
    (StatusCode::NO_CONTENT, ()).into_response()
}



Regarding the CORS issue in Rust with Axum, Diesel, and PostgreSQL, it seems there is some confusion about which dependency to use. The dependencies `axum-cors`, `tower_http::cors::CorsLayer`, and `axum_util::cors::CorsLayer` are mentioned, but there are reports of errors at the code level.

For specific issues related to Rust and its frameworks, it is often helpful to consult the latest documentation, community forums, or GitHub repositories for the most up-to-date information and potential fixes.

报错信息
```json
[
    {
        "resource": "/d:backend/src/routes.rs",
        "owner": "rustc",
        "code": {
            "value": "Click for full compiler diagnostic",
            "target": {
                "$mid": 1,
                "path": "/diagnostic message [4]",
                "scheme": "rust-analyzer-diagnostics-view",
                "query": "4",
                "fragment": "file:///d%3A/backend/src/routes.rs"
            }
        },
        "severity": 8,
        "message": "no function or associated item named `new` found for struct `CorsLayer` in the current scope\nfunction or associated item not found in `CorsLayer`",
        "source": "rustc",
        "startLineNumber": 56,
        "startColumn": 27,
        "endLineNumber": 56,
        "endColumn": 30
    }
]

The JSON snippet appears to be a diagnostic message from a Rust compiler, indicating an error in the code. The message specifically points out that no function or associated item named `new` was found for the struct `CorsLayer` in the current scope. This error is found in the file `routes.rs` at line 56, columns 27 to 30. This is consistent with your earlier mention of issues with the CORS implementation in your Rust project.


评论区

写评论
作者 C-Jeril 2024-01-19 17:47

最后我是用use tower_http::cors::{AllowOrigin, CorsLayer};来解决了。

bestgopher 2024-01-19 11:58

CorsLayer 没有new方法?

1 共 2 条评论, 1 页