【问题标题】:Blocked by CORS on Actix Web backend with Cors::permissive()使用 Cors::permissive() 在 Actix Web 后端被 CORS 阻止
【发布时间】:2023-04-04 03:38:01
【问题描述】:

我正在尝试使用 Rust 构建一个简单的后端,但我一直遇到 CORS 错误。

我的反应前端说:

Access to XMLHttpRequest at 'http://127.0.0.1:3002/auth' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是我的后端代码:

// Route Config //
pub fn routes(cfg: &mut web::ServiceConfig) { 
    cfg.route("/auth", web::get().to(auth_handler));
}

// Handler Config //
async fn auth_handler() -> impl Responder { 
    HttpResponse::Ok().json("Works")
}

#[actix_rt::main]
async fn main() -> io::Result<()> { 
    let app = move || App::new().configure(routes);
    let _cors = Cors::permissive();
    HttpServer::new(app).bind("127.0.0.1:3002")?.run().await
}

据我了解,CORS::permissive() 函数应该允许所有跨站点交互工作。是我误解了文档,还是我执行错误?

【问题讨论】:

    标签: rust actix-web


    【解决方案1】:

    您需要通过.wrap() 实际使用App 中的Cors 中间件:

    let app = move || App::new().wrap(Cors::permissive()).configure(routes);
                             // ^^^^^^^^^^^^^^^^^^^^^^^^^
    

    更多配置信息here

    【讨论】:

    • 行得通!感谢您的快速回复
    猜你喜欢
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 2021-10-16
    • 2021-05-31
    • 2019-08-03
    • 1970-01-01
    相关资源
    最近更新 更多