CORS - 在请求的资源上不存在 'Access-Control-Allow-Origin' 头部信息。

5
我想要从一个使用REACT编写的前端表单向一个使用C#编写的API服务器POST数据。
为此,我编写了以下内容: 对于前端:
const [analysis, setAnalysis] = useState(null);

const headers = {
    'Content-Type': 'application/json;charset=UTF-8',
    "Access-Control-Allow-Origin": "*",
    'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': '*'
};


useEffect(() => {
    axios.get(baseURL, {
        mode: 'cors',
        headers: headers,
    }).then((response) => {
        setAnalysis(response.analysis);
    });
}, []);

针对后端:
builder.Services.AddCors(options =>
{
    options.AddPolicy("MyMyAllowCredentialsPolicy",
        builder =>
        {
            builder.AllowAnyMethod()
                .AllowAnyHeader()
                .SetIsOriginAllowed(origin => true) // allow any origin
                .AllowCredentials(); // allow credentials
        }
    );
}); 

然而,我有以下问题: enter image description here 我尝试了很多不同的配置,但都没有成功。有没有人知道问题在哪里,怎么解决?
提前感谢, Alexia
[版面]
根据所有建议,我改变了我的代码。
前端部分:
const headers = {
        'Content-Type': 'application/json;charset=UTF-8',
    };


    useEffect(() => {
        axios.get(baseURL, {
            mode: 'cors',
            headers: headers,
        }).then((response) => {
            setAnalysis(response.analysis);
        });
    }, []);

The back-end :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddCors(options =>
{
    options.AddPolicy(MyAllowSpecificOrigins,
                          builder =>
                          {
                              builder.WithOrigins("http://localhost:3000/")
                                                  .AllowAnyHeader()
                                                  .AllowAnyMethod();
                          });
});

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();


var app = builder.Build();

app.UseCors(MyAllowSpecificOrigins);

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.MapControllers();

app.Run();

使用这个配置,我仍然有:
Access to XMLHttpRequest at 'https://localhost:7067/...?id=1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

请理解您正在做的事情:将 .SetIsOriginAllowed(origin => true).AllowCredentials() 一起使用是不安全的!CORS 不容小觑。 - jub0bs
1
谢谢提醒!实际上,我已经删除了“allowcredentials”,但仍然出现CORS错误。由于所有内容都在本地主机上运行,我只是为了确认而尝试了一下。 - Alexia
首先从您的请求中删除所有 Access-Control-Allow-* 标头。这些标头是响应标头,而不是请求标头。采取这第一步可能会改善情况。 - jub0bs
1
我解决了所有问题!感谢您的帮助! - Alexia
6
当然,如果你发表你的解决方案就太好了。 - Doug Wilson
显示剩余5条评论
1个回答

1

我曾遇到类似的问题,不得不对实际的API代码进行更改,因此请在您的Start.cs文件中添加以下内容。建议您首先在本地主机上尝试,然后再将更改部署到实际的API所在位置。

public class Startup
{
    private readonly string _MyCors = "MyCors";
    .
    .
    .
    public void ConfigureServices(...)
    {
        .
        .
        .
        //Under your services.AddControllers();
        services.AddCors(options =>
        {
            options.AddPolicy(name: _MyCors, builder =>
            {
                //for when you're running on localhost
                builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost") 
                .AllowAnyHeader().AllowAnyMethod();


                //builder.WithOrigins("url from where you're trying to do the requests")
            });
        });
    }
    public void Configure(.....)
    {
        //before the app.UseAuthorization & app.UseEndpoints
        app.UseCors(_MyCors);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接