【问题标题】:CORS problem with React and Entity Framework Core Web APIReact 和 Entity Framework Core Web API 的 CORS 问题
【发布时间】:2020-09-06 22:21:48
【问题描述】:

从 2 天以来,我一直在尝试使用 fetch 方法进行简单的 http 请求,但我无法摆脱 cors 错误。我将 http 标头放入 .htaccess 文件,但它似乎不起作用。

fetch('https://localhost:44326/api/Users', {
        header: {
            "Content-Type": "application/json"
        },
        method: 'POST',
        body: JSON.stringify({ obj })
    })
        .then(response => console.log(response));

我一直得到有关 Access-Control-Allow-Origin 标头丢失的信息。有什么想法吗?

启动配置:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddDbContext<ImageContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("ImageDB"));
        });

        services.AddCors(c => c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin()));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

    }
}

【问题讨论】:

  • 你能分享你的startup类配置吗?
  • 记得在app.UseRouting()后面加上app.UseCors("AllowOrigin");

标签: reactjs entity-framework-core cors asp.net-core-webapi


【解决方案1】:

不要忘记设置您的 credentials 参数...

fetch('https://localhost:44326/api/Users', {
        credentials: 'same-origin',
        header: {
            "Content-Type": "application/json"
        },
        method: 'POST',
        body: JSON.stringify({ obj })
    })

same-origin 用于当 React 应用程序在与其获取的服务器相同的域名上运行时。对于不同的域,将其更改为 include。查看Fetch() MDN Documents 上的 fetch() API。

或者,服务器端,您可以正确设置标头...

<?php

     header('Access-Control-Allow-Origin: https://mozilla.org');

?>

这是一个将 ReactApp 托管在 mozilla.org 上的示例。 CORS MDN Documents。希望这会有所帮助!

【讨论】:

  • 你尝试了什么?将凭据设置为同源和包含?您是否在服务器端发送了标头?您是否使用 cURL 检查它以查看它的显示?也许尝试将标题设置为Access-Control-Allow-Origin: *
  • 我尝试了你上面提出的一切。顺便说一句,我不使用 php。
  • 清除缓存?也可以尝试credentials: omit,并将标题来源设置为*
  • 是的,我清除并尝试了各种可能的凭据和标题。还是找不到解决办法...
  • 嗯,我想不出别的了。我从链接中重新阅读了文档,这应该是它应该如何工作的。标头确实需要在其他内容之前发送,但您可能知道这一点。
猜你喜欢
  • 2021-07-27
  • 2020-12-14
  • 2018-04-12
  • 1970-01-01
  • 2019-04-13
  • 1970-01-01
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多