@@ -22,18 +22,39 @@ pub fn create_cors() -> Cors {
2222
2323 if cors_enabled {
2424 log:: info!( "CORS 已启用,允许来源: {}" , cors_origin) ;
25- Cors :: default ( )
26- . allowed_origin ( & cors_origin)
27- . allowed_origin ( & format ! ( "http://127.0.0.1:{}" , port) )
28- . allowed_origin ( & format ! ( "http://localhost:{}" , port) )
29- . allowed_methods ( vec ! [ "GET" , "POST" , "PUT" , "DELETE" ] )
30- . allowed_headers ( vec ! [
31- actix_web:: http:: header:: AUTHORIZATION ,
32- actix_web:: http:: header:: ACCEPT ,
33- actix_web:: http:: header:: CONTENT_TYPE ,
34- ] )
35- . supports_credentials ( )
36- . max_age ( 3600 )
25+
26+ // 如果 cors_origin 是 "*",则发送通配符响应头而不是在 allowed_origin 中使用 "*"
27+ if cors_origin == "*" {
28+ Cors :: default ( )
29+ . send_wildcard ( )
30+ . allowed_methods ( vec ! [ "GET" , "POST" , "PUT" , "DELETE" ] )
31+ . allowed_headers ( vec ! [
32+ actix_web:: http:: header:: AUTHORIZATION ,
33+ actix_web:: http:: header:: ACCEPT ,
34+ actix_web:: http:: header:: CONTENT_TYPE ,
35+ ] )
36+ . supports_credentials ( )
37+ . max_age ( 3600 )
38+ } else {
39+ // 支持逗号分隔的多个源
40+ let origins: Vec < & str > = cors_origin. split ( ',' ) . map ( |s| s. trim ( ) ) . collect ( ) ;
41+ let mut cors = Cors :: default ( ) ;
42+
43+ for origin in origins {
44+ cors = cors. allowed_origin ( origin) ;
45+ }
46+
47+ cors. allowed_origin ( & format ! ( "http://127.0.0.1:{}" , port) )
48+ . allowed_origin ( & format ! ( "http://localhost:{}" , port) )
49+ . allowed_methods ( vec ! [ "GET" , "POST" , "PUT" , "DELETE" ] )
50+ . allowed_headers ( vec ! [
51+ actix_web:: http:: header:: AUTHORIZATION ,
52+ actix_web:: http:: header:: ACCEPT ,
53+ actix_web:: http:: header:: CONTENT_TYPE ,
54+ ] )
55+ . supports_credentials ( )
56+ . max_age ( 3600 )
57+ }
3758 } else {
3859 log:: info!( "CORS 已禁用,允许所有来源" ) ;
3960 Cors :: default ( )
0 commit comments