c# - react +ASP.NET.Core : No 'Access-Control-Allow-Origin' header is present on the requested resource

标签 c# reactjs asp.net-core .net-core

其实这不是一个重复的帖子,我知道标题的一部分在stackoverflow中问过很多次|社区,我阅读了所有帖子和答案,但我认为我的问题和我使用的技术不同。

首先我要提到 ASP.NET Core WEB/API 是我的后端应用程序,Reactjs 是我的前端应用程序。

我阅读了有关 CORS 的内容,我发现我必须在 ASP.NET 应用程序上启用 CORS 并放置 'Access-Control -Allow-Origin':'*' 在我的请求 header 上,但我在调用 api 时仍然出现以下错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

这是我的 Startup.csCORS 相关的代码:

public void ConfigureServices(IServiceCollection services)
{

    // other lines of code
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll",
            builder =>
            {
                builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            });
    });

    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll"));
    });
    // other lines of code
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    app.UseCors("AllowAll");
    app.UseAuthentication();
    app.UseMvc();
}

这是我的 react 代码:

function save(message) {
    const requestOptions = {
        method: 'POST',
        mode: 'cors',
        headers: { ...authHeader(), 
            'Content-Type': 'application/json',    
            'Access-Control-Allow-Origin':'*',

    },
        body: JSON.stringify(message)               
    };
    return fetch(config.apiUrl + '/message/save', requestOptions).then(handleResponse, handleError);
}

感谢您的回复。

最佳答案

我最近遇到了类似的问题。在我的例子中,当我在我的 ConfigureServices 方法和这部分代码中添加 services.AddCors(); 时它开始工作

app.UseCors(builder => builder
   .AllowAnyOrigin()
   .AllowAnyMethod()
   .AllowAnyHeader()
   .AllowCredentials());

在我的 Configure 方法中。请记住在这两种情况下添加那些 BEFORE UseMvc() 调用。

关于c# - react +ASP.NET.Core : No 'Access-Control-Allow-Origin' header is present on the requested resource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52896068/

相关文章:

c# - IsSelected == False 的 ListBox DataTrigger 在人口上触发?

c# - 如何以编程方式使标签的某些部分在 Windows 窗体中加粗?

reactjs - 使用react-redux connect时如何流动类型 Prop

asp.net-core - userManager.FindByName 不返回角色

asp.net-core - 如何存储具有到期日期的对象

c# - 具有 DbContext 的单例 - 在 Startup.cs 中创建实例

c# - 通过 C# 代码在远程机器上启动和停止 IIS

c# - 从 C#/WPF 到 C++/Qt 的转换 : dinamically generate a button list

javascript - CSS。让父级有子级宽度

javascript - OnKeyPress 不触发