.net - 部署到服务器时出现 CORS 问题
问题描述
我在同一台服务器上部署了两个项目。其中一个是 Angular 项目,另一个是 Angular 项目调用的.net CORE 中的 API。在本地我没有这个问题,但是在服务器上,每次我调用 API 时,我都会在浏览器控制台中收到以下错误消息:
访问 XMLHttpRequest 在 >' http://myIPAdress:81/Configuration/CODE_CLIENT ' 从源 >' http://myIPAdress ' 已被 CORS 策略阻止:不存在'Access-Control->Allow-Origin'标头请求的资源
我推断问题来自 .NET Core 项目。我已经在 StackoverFlow 上尝试过建议的解决方案,但没有成功。这是我在 .net Core 端的代码:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new
CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
});
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://localhost:80").AllowAnyHeader()
.AllowAnyMethod());
});
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
loggerFactory.AddDebug(LogLevel.Information);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Shows UseCors with named policy.
app.UseCors("AllowSpecificOrigin");
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
}
在 Angular 方面,我这样调用我的 API:
getConf(code : string){
var url = "http://MyIPAdress/Configuration";
return this.http.get<any>(url +'/'+ code)
}
在本地,我通过我的 API 访问数据,但不是在服务器上,有人知道为什么吗?
对不起我的英语和我的代码我开始编程
编辑:我在服务器的 IIS 中添加了一个 HTTP 响应:Access-Control-Allow-Origin。现在我没有同样的错误,但是这个:
响应中“Access-Control-Allow-Credentials”标头的值是 >'',当请求的凭据模式为“包含”时,该值必须为“真”。XMLHttpRequest 发起的请求的 >credentials 模式由 >withCredentials 属性控制。
解决方案
中builder => builder.WithOrigins("http://localhost:80").AllowAnyHeader()
,同时http://localhost:80
添加服务器 IP 地址
像这样:
builder.WithOrigins("http://localhost:80","http://serverIPAddress.com");
推荐阅读
- python - 霍夫圆总是不返回
- android - 程序类型已经存在:com.google.android.gms.internal.measurement.zzst"
- flutter - 状态变化的集团导航
- javascript - 刷新 React 中元素的位置未更改
- powershell - 在 ps1 中使用全局变量
- botframework - 无法将 Bot 与 Skype for Business 连接
- python - 使用tensorflow的flask应用的响应时间,随着请求的数量呈指数增长
- css - 满足 2 个(两个)条件的 CSS 选择器
- php - 为什么laravel中不存在错误Builder::query?
- php - 如何在 Dockerfile 中自动插入 IP 地址