简体   繁体   English

React+ASP.NET.Core:请求的资源上不存在“Access-Control-Allow-Origin”标头

[英]React+ASP.NET.Core : No 'Access-Control-Allow-Origin' header is present on the requested resource

Actually this is not a duplication post,I know a part of the title asked many times in stackoverflow community, I read all posts, and answers, but I think my problem and technologies which I used are different.其实这不是一个重复的帖子,我知道在stackoverflow社区多次询问标题的一部分,我阅读了所有帖子和答案,但我认为我的问题和我使用的技术是不同的。

First of all I should mention ASP.NET Core WEB/API is my back-end-app and Reactjs is my front Application.首先,我应该提到ASP.NET Core WEB/API是我的后端应用程序,而Reactjs是我的前端应用程序。

I read about CORS and I found out I must enable CORS on ASP.NET App and put 'Access-Control-Allow-Origin':'*' on my request's header, but I still have the below error while I call an api:我阅读了有关CORS ,发现我必须在ASP.NET应用程序上启用CORS并将'Access-Control-Allow-Origin':'*'放在我的请求标头上,但是在调用 api 时仍然出现以下错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource.请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin ' http://localhost:8080 ' is therefore not allowed access.因此,不允许访问 Origin ' http://localhost:8080 '。 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.响应的 HTTP 状态代码为 500。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

This is my Startup.cs code related to CORS :这是我与CORS相关的Startup.cs代码:

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();
}

This is my react code:这是我的反应代码:

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);
}

Thanks for your responding.感谢您的回复。

I had a similar problem recently.我最近遇到了类似的问题。 In my case it started working when I added services.AddCors();就我而言,当我添加services.AddCors();时它开始工作services.AddCors(); in my ConfigureServices method and this part of code在我的ConfigureServices方法和这部分代码中

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

in my Configure method.在我的Configure方法中。 Remember to add those BEFORE UseMvc() call in both cases.请记住在这两种情况下UseMvc() 调用之前添加那些。

After two difficult days finally I found out how can I fix my problem.经过两天艰难的日子,我终于找到了如何解决我的问题。 Actually one of your comment was a nice clue for me.实际上,你的一条评论对我来说是一个很好的线索。

@kirk-larkin said: @kirk-larkin 说:

The response had HTTP status code 500 is key here.响应具有 HTTP 状态代码 500 是这里的关键。 When there's an exception in your ASP.NET Core project, the CORS headers are cleared.当 ASP.NET Core 项目中出现异常时,会清除 CORS 标头。 You should try and find out why an exception is being thrown.您应该尝试找出抛出异常的原因。

I traced my code many times, then i found out I forget to register a service which I used in my controller in Startup.cs.我多次跟踪我的代码,然后我发现我忘记在 Startup.cs 中注册我在控制器中使用的服务。

I called these below code in Startup.cs and my problem solved.我在 Startup.cs 中调用了以下代码,我的问题解决了。

services.AddScoped<IMessageService, MessageService>();

With ASP.NET Core 2.1, when the controller throws an exception, which results in an error 500, the CORS headers are not sent.对于 ASP.NET Core 2.1,当控制器抛出异常并导致错误 500 时,不会发送 CORS 标头。 This should be fixed in the next version but until then you could use a middleware to fix this.这应该在下一个版本中修复,但在那之前你可以使用中间件来解决这个问题。

see

Also note that with credentials you need to explicitly add WithOrigins with host and port since most browsers simply ignore it otherwise (see https://stackoverflow.com/a/19744754/2477619 ):另请注意,使用凭据,您需要使用主机和端口显式添加WithOrigins ,因为大多数浏览器只会忽略它(请参阅https://stackoverflow.com/a/19744754/2477619 ):

  app.UseCors(builder =>
    builder
      .WithOrigins("http://localhost:4200")
      .AllowAnyHeader()
      .AllowAnyMethod()
      .AllowCredentials()
  );

I had the same problem when I was making my app. 我在制作应用程序时遇到了同样的问题。 I downloaded this chrome extension and the problem was gone. 我下载了这个chrome扩展程序,问题就消失了。 Maybe it helps for you? 也许它对你有帮助?

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

As said by @Siavash the fact that it is returning 500 may indicate there is an issue with the build.正如@Siavash 所说,它返回 500 的事实可能表明构建存在问题。 I was having this problem today as it was working fine on localhost but was failing when deployed.我今天遇到了这个问题,因为它在本地主机上运行良好,但在部署时失败了。

To debug the error, find this line in your web.config file in the root of the IIS directory:要调试错误,请在 IIS 目录根目录下的 web.config 文件中找到以下行:

<aspNetCore processPath="dotnet" arguments=".\CarpetrightBackend.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />

Change stdoutLogEnabled="false" to true and then you will be able to see the error in the log file generated.将 stdoutLogEnabled="false" 更改为 true,然后您将能够在生成的日志文件中看到错误。

In my case I forgot to incude some static csv files when deploying that the program needed to reference and return data from it.在我的情况下,我在部署程序时忘记包含一些静态 csv 文件,该程序需要从中引用和返回数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.Net核心WebAPI - 请求的资源上没有“Access-Control-Allow-Origin”标头 - ASP.Net Core WebAPI - No 'Access-Control-Allow-Origin' header is present on the requested resource ASP.NET Web窗体:所请求的资源上不存在“ Access-Control-Allow-Origin”标头 - ASP.NET Web Forms: No 'Access-Control-Allow-Origin' header is present on the requested resource 反应 .NET 启用 CORS - 没有'Access-Control-Allow-Origin' header 出现在请求的资源上 - React .NET Enable CORS - No 'Access-Control-Allow-Origin' header is present on the requested resource CORS所请求的资源上没有“ Access-Control-Allow-Origin”标头 - CORS No 'Access-Control-Allow-Origin' header is present on the requested resource CORS - 没有'Access-Control-Allow-Origin' header 存在于请求的资源上 - CORS - No 'Access-Control-Allow-Origin' header is present on the requested resource 请求的资源上不存在“ Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource 问题:请求的资源上不存在“Access-Control-Allow-Origin”header - Issue: No 'Access-Control-Allow-Origin' header is present on the requested resource In.Net Core 2.1 Web API 用于 PUT 和 DELETE,仅为什么请求的资源上存在“No 'Access-Control-Allow-Origin' header” - In .Net Core 2.1 Web API for PUT and DELETE only why “No 'Access-Control-Allow-Origin' header is present on the requested resource” .NET 5 对预检请求的响应未通过访问控制检查:没有'Access-Control-Allow-Origin' header 存在于请求的资源上 - .NET 5 Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource 在Asp.net Core 2.1的Angular 6中不存在“ Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present Angular 6 with Asp.net Core 2.1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM