You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用actix-web时缺失Access-Control-Allow-Origin的问题求助

解决CORS header缺失问题

核心原因:Origin配置不匹配

你的actix-web服务器中allowed_origin配置多了末尾的斜杠,浏览器发送的Origin是http://localhost:3000(不带路径斜杠),和配置的http://localhost:3000/不匹配,导致CORS策略未生效。

修复步骤

  1. 修正Origin配置
    将服务器代码中的:

    .allowed_origin("http://localhost:3000/")
    

    修改为:

    .allowed_origin("http://localhost:3000")
    
  2. 确认中间件顺序
    你的代码已经将wrap(cors)放在service(myfunc)之前,这是正确的顺序,确保CORS中间件能拦截所有请求。

  3. 验证依赖兼容性
    actix-cors 0.6.1与actix-web 4.x版本兼容,无需调整Cargo.toml依赖。

修复后的完整服务器代码

#[actix_web::main]
async fn main() {
    HttpServer::new(move || {
        let cors = Cors::default()
            .allowed_origin("http://localhost:3000")
            .allowed_methods(vec!["GET", "POST"])
            .allowed_header(actix_web::http::header::ACCEPT)
            .allowed_header(actix_web::http::header::CONTENT_TYPE)
            .max_age(3600);

        App::new()
            .wrap(cors)
            .service(myfunc)
    })
    .bind(("0.0.0.0", 8080))
    .unwrap()
    .run()
    .await
    .unwrap();
}

额外检查

  • 重启actix-web服务器,确保配置变更生效。
  • 无需手动处理OPTIONS预检请求,actix-cors中间件会自动完成这部分逻辑。

内容的提问来源于stack exchange,提问作者Muhammad Najid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 19:46:18