使用actix-web时缺失Access-Control-Allow-Origin的问题求助
解决CORS header缺失问题
核心原因:Origin配置不匹配
你的actix-web服务器中allowed_origin配置多了末尾的斜杠,浏览器发送的Origin是http://localhost:3000(不带路径斜杠),和配置的http://localhost:3000/不匹配,导致CORS策略未生效。
修复步骤
修正Origin配置
将服务器代码中的:.allowed_origin("http://localhost:3000/")修改为:
.allowed_origin("http://localhost:3000")确认中间件顺序
你的代码已经将wrap(cors)放在service(myfunc)之前,这是正确的顺序,确保CORS中间件能拦截所有请求。验证依赖兼容性
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
相关产品推荐
相关产品推荐

