其实这不是一个重复的帖子,我知道标题的一部分在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.cs
与 CORS
相关的代码:
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/