简体   繁体   English

Angular 6 - 对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头

[英]Angular 6 - Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header

I'm getting CORS error when calling a POST or DELETE Core API from my Angular application. 从我的Angular应用程序调用POST或DELETE Core API时出现CORS错误。

My Core Web API's are configured with Windows Authentication. 我的Core Web API配置了Windows身份验证。 And [Authorize] attribute is at controller level. 并且[Authorize]属性处于控制器级别。 Whenever I pass a GET request from Angular, the request is getting authorized and I'm getting the response back. 每当我从Angular传递GET请求时,请求都会获得授权,我会收到响应。

When sending a POST request from Angular to Core API, 从Angular向Core API发送POST请求时,

1) If I pass data as FormData from Angular service to Core API, it is working fine. 1)如果我将FormData中的数据从Angular服务传递到Core API,它工作正常。

2) If I pass data as Model from Angular service to Core API, I'm getting the below error 2)如果我将数据作为模型从Angular服务传递到Core API,我收到以下错误

Failed to load http://localhost:63854/api/sampleController/1 : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 无法加载http:// localhost:63854 / api / sampleController / 1 :对预检请求的响应未通过访问控制检查:请求的资源上没有“Access-Control-Allow-Origin”标头。 Origin ' http://localhost:52871 ' is therefore not allowed access 因此不允许来源' http:// localhost:52871 '访问

Here is Startup.cs 这是Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options => options.AddPolicy("AllowAll",
        builder => builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials()));

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("AllowAll");

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseMvc();
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "APIs"));
    app.UseMvcWithDefaultRoute();
}

Core API action method: 核心API操作方法:

[Authorize]
[Produces("application/json")]
[Route("api/someRoute")]

public class someController : Controller
{
    [HttpPost]
    [Route("update")]
    public async Task<HttpResponseMessage> UpdateAccessType([FromBody] TestModel modalObj)
    {
         //code..
    }

    [HttpDelete("{id}")]
    public async Task<HttpResponseMessage> DeleteAccessType(string id)
    {
        //code..
    }
}

Angular Service: accessType is constructed in component, and passed as object to angular service. 角度服务:accessType在组件中构造,并作为对象传递给角度服务。

updateAccessType(accessType) {
    return this.http.post(this.apiUrl + "api/someController/update", accessType);
}

deleteAccessType(accessLookupId: string) {
    return this.http.delete(this.apiUrl + "api/someController/" + accessLookupId);
}

Complete error message (But this is happening only when passing data as modal, not happening when passing data as FormData) - Both DELETE and POST requests gives the same exception. 完整的错误消息(但这只在将数据作为模态传递时发生,而不是在将数据作为FormData传递时发生) - DELETE和POST请求都给出了相同的异常。

HTTP Error 401.2 - Unauthorized - You are not authorized to view this page due to invalid authentication headers HTTP错误401.2 - 未经授权 - 由于身份验证标头无效,您无权查看此页面

I like to pass model from Angular to Core API instead of FormData. 我喜欢将模型从Angular传递给Core API而不是FormData。

Try using below in Configure method instead: 请尝试在Configure方法中使用以下内容:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
}

If you want to use Cors, in combination with Windows Authentication, you have to enable also the "Anonymous Authentication". 如果要使用Cors,结合Windows身份验证,还必须启用“匿名身份验证”。 Tried all other solutions, but with no success. 尝试了所有其他解决方案,但没有成功。

In Angular, I had to implement HttpInterceptor to put it to work. 在Angular中,我必须实现HttpInterceptor才能使它工作。

import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
  HttpEvent
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';

@Injectable()
export class WithCredentialsInterceptor implements HttpInterceptor {
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    request = request.clone({
      withCredentials: true
    });

    return next.handle(request);
  }

暂无
暂无

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

相关问题 对预检请求的响应未通过访问控制检查:否&#39;Access-Control-Allow-Origin&#39; - Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' 在 ASP.NET 中,对预检请求的响应未通过访问控制检查:No &#39;Access-Control-Allow-Origin&#39; 标头 - In ASP.NET, Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header .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 对预检请求的响应未通过访问控制检查:响应中“ Access-Control-Allow-Credentials”标头的值为“ - Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' 如何处理错误“对预检请求的响应未通过访问控制检查:&#39;Access-Control-Allow-Credentials&#39;的值” - How to handel error “Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials'” 对预检请求的响应未通过访问控制检查(Angular2) - Response to preflight request doesn't pass access control check (Angular2) ASP.NET Core Web API + Angular 对预检请求的响应未通过访问控制检查:预检请求不允许重定向 - ASP.NET Core Web API + Angular Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request 使用C#和jQuery在预检请求中的请求资源上不存在“ Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource in preflight request using c# and jQuery CORS WCF:对预检请求的响应未通过访问控制 - CORS WCF: Response to preflight request doesn't pass access control ASP.net核心信号器角度客户端,错误“对预检请求的响应未通过访问控制检查” - ASP.net core signalr angular client, error “Response to preflight request doesn't pass access control check”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM