Skip to content

web - CORS跨域

nginx
location ^~ /starfishapi {
    # CORS 配置 - 允许所有来源
    add_header 'Access-Control-Allow-Origin'   '*';
    add_header 'Access-Control-Allow-Methods'  'GET, POST, PUT, DELETE, OPTIONS';
    add_header 'Access-Control-Allow-Headers'  'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';

    # 处理 OPTIONS 请求
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
    }

    proxy_pass             http://192.168.3.30:5169/starfishapi;
    proxy_set_header       Host                 $host;
    proxy_set_header       X-Real-IP            $remote_addr;
    proxy_set_header       X-Forwarded-For      $proxy_add_x_forwarded_for;
    proxy_set_header       X-Forwarded-Proto    $scheme;
    proxy_set_header       X-Forwarded-Protocol $scheme;
    proxy_set_header       X-Forwarded-Host     $http_host;
    proxy_buffering        off;
}
csharp
// 允许跨域,默认策略
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy =>
    {
        policy
            // .WithOrigins("http://localhost:5173", "http://www.contoso.com")
            .AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod();
    });
});

//位置在UseSwagger、UseAuthorization之前
app.UseCors();

上次更新时间:

最近更新