为啥我收到 Cors 错误:...已被 CORS 政策阻止

Posted

技术标签:

【中文标题】为啥我收到 Cors 错误:...已被 CORS 政策阻止【英文标题】:Why do im receving the Cors Error :...has been blocked by CORS policy为什么我收到 Cors 错误:...已被 CORS 政策阻止 【发布时间】:2020-03-07 15:15:58 【问题描述】:

为什么我仍然面临这个错误

从源“http://localhost:4200”访问“http://localhost:21063/api/clints”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

即使我在 asp.net core web api 中启用了它 Startup.cs

services.AddCors(options =>
            
                options.AddPolicy("enableCors",
                builder =>
                
                    builder.WithOrigins("http://localhost:4200")
                                        .AllowAnyHeader()
                                        .AllowAnyMethod()
                                        .AllowCredentials()
                                        .Build();
                );
            );


        

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        
            if (env.IsDevelopment())
            
                app.UseDeveloperExceptionPage();
            

            app.UseMvc();
            app.UseCors("enableCors");
        
    


这是我的 Controllel.cs

... [Route("api/[controller]")]
    [ApiController]
    [EnableCors("enableCors")]
    public class ClintsController : ControllerBase
    
        private readonly OneClickDBContext _context;

        public ClintsController(OneClickDBContext context)
        
            _context = context;
         
...

我通常从同一个API获取数据的字符串,当我发布时发生了这个错误。

我的 componanet.ts

...
  ngOnInit() 
    this.Service.getAllClients()
      .subscribe(data => this.clients = data);

    //post data
    this.Service.client = 
      id: 0,
      name: null,
      phone: null,
      address: null,
      account: 0,
      nots: null,
      branchId: 0,
      type: null,
    

  PostClient() 
    if (this.Service.client.id == 0) 

      this.Service.addClient().subscribe(res => 
        this.Service.getAllClients()
      ,
      )
    else 
      this.Service.editClient().subscribe(res => 
        this.Service.getAllClients()
      ,
        err => 
          console.log(err)
        )
    
  
...

service.ts

export class ClientsService 

  clientsUrl="http://localhost:21063/api/clints"

  client:Clients;


  constructor(private http:HttpClient)  
getAllClients():Observable<Clients[]>
    return this.http.get<Clients[]>(this.clientsUrl);


addClient()
return this.http.post(this.clientsUrl,this.client)

  

editClient()
  return this.http.put(this.clientsUrl + "/" + this.client.id,this.client)

     

html 表单

<div class="modal fade" id="add_client" tabindex="-1" role="dialog" aria-labelledby="add_clientTitle"aria-hidden="true">
     <div class="modal-dialog modal-dialog-centered" role="document">
          <div class="modal-content">
               <div class="modal-header">
                    <h5 class="modal-title" id="add_clientTitle">إضافة عميل جديد</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="margin: -1rem -1rem;">

                           <span aria-hidden="true">&times;</span>
                         </button>
                    </div>
                           <div class="modal-body">
                               <form class="row" ngForm="form" (submit)="post_client()"> 
                                     <div class="form-group col-12 col-md-6">
                                          <div class="modal_group group">
                                               <input type="text" required name="clientName" [(ngModel)]="Service.client.name">
                                                    <span class="highlight"></span>
                                                    <span class="bar"></span>
                                                    <label>اسم العميل</label>
                                             </div>
                                         </div>
                                              <div class="form-group col-12 col-md-6">
                                                 <div class="modal_group group">
                                                     <input type="text" required name="clientPhone" [(ngModel)]="Service.client.phone">
                                                        <span class="highlight"></span>
                                                        <span class="bar"></span>
                                                        <label>الهاتف </label>
                                                    </div>
                                                </div>
                                                <div class="form-group col-12 col-md-6">
                                                    <div class="modal_group group">
                                                        <input type="text" required name="clientAddress" [(ngModel)]="Service.client.address">
                                                        <span class="highlight"></span>
                                                        <span class="bar"></span>
                                                        <label>العنوان</label>
                                                    </div>
                                                </div>
                                                <div class="form-group col-12 col-md-6">
                                                    <div class="modal_group group ">
                                                        <input type="text" required name="clientAcc" [(ngModel)]="Service.client.account">
                                                        <span class="highlight"></span>
                                                        <span class="bar"></span>
                                                        <label>الرصيد السابق</label>
                                                    </div>
                                                </div>
                                                <div class="form-group col-12 col-md-6">
                                                    <div class="modal_group group">
                                                        <input type="text" required name="clientNote" [(ngModel)]="Service.client.nots">
                                                        <span class="highlight"></span>
                                                        <span class="bar"></span>
                                                        <label>ملاحظات</label>
                                                    </div>
                                                </div>
                                            </form>
                                        </div>
                                        <!--end modal-body-->
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary"
                                                data-dismiss="modal">إلغاء</button>
                                            <button type="button" class="btn btn-primary" (click)= " PostClient()" >حفظ</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!--end Modal -->

请注意,当我在 Firefox 中打开时,错误是

跨域请求被阻止:同源策略不允许读取位于http://localhost:21063/api/clints 的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)。

错误 Object headers: …, status: 0, statusText: "Unknown Error", url: "http://localhost:21063/api/clints", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost:21063/api/clints: 0 Unknown错误”,错误:错误。

更新

我的控制器.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OneClickAPI.Models;

namespace OneClickAPI.Controllers

    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("enableCors")]
    public class ClintsController : ControllerBase
    
        private readonly OneClickDBContext _context;

        public ClintsController(OneClickDBContext context)
        
            _context = context;
        

        // GET: api/Clints
        [HttpGet]
        public IEnumerable<ClintsTbl> GetClintsTbl()
        
            return _context.ClintsTbl;
        

        // GET: api/Clints/5
        [HttpGet("id")]
        public async Task<IActionResult> GetClintsTbl([FromRoute] int id)
        
            if (!ModelState.IsValid)
            
                return BadRequest(ModelState);
            

            var clintsTbl = await _context.ClintsTbl.FindAsync(id);

            if (clintsTbl == null)
            
                return NotFound();
            

            return Ok(clintsTbl);
        

        // PUT: api/Clints/5
        [HttpPut("id")]
        public async Task<IActionResult> PutClintsTbl([FromRoute] int id, [FromBody] ClintsTbl clintsTbl)
        
            if (!ModelState.IsValid)
            
                return BadRequest(ModelState);
            

            if (id != clintsTbl.Id)
            
                return BadRequest();
            

            _context.Entry(clintsTbl).State = EntityState.Modified;

            try
            
                await _context.SaveChangesAsync();
            
            catch (DbUpdateConcurrencyException)
            
                if (!ClintsTblExists(id))
                
                    return NotFound();
                
                else
                
                    throw;
                
            

            return NoContent();
        

        // POST: api/Clints
        [HttpPost]
        public async Task<IActionResult> PostClintsTbl([FromBody] ClintsTbl clintsTbl)
        
            if (!ModelState.IsValid)
            
                return BadRequest(ModelState);
            

            _context.ClintsTbl.Add(clintsTbl);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetClintsTbl", new  id = clintsTbl.Id , clintsTbl);
        

        // DELETE: api/Clints/5
        [HttpDelete("id")]
        public async Task<IActionResult> DeleteClintsTbl([FromRoute] int id)
        
            if (!ModelState.IsValid)
            
                return BadRequest(ModelState);
            

            var clintsTbl = await _context.ClintsTbl.FindAsync(id);
            if (clintsTbl == null)
            
                return NotFound();
            

            _context.ClintsTbl.Remove(clintsTbl);
            await _context.SaveChangesAsync();

            return Ok(clintsTbl);
        

        private bool ClintsTblExists(int id)
        
            return _context.ClintsTbl.Any(e => e.Id == id);
        
    

更新2 预览

An unhandled exception occurred while processing the request.
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ClintsTbl_branchTbl". The conflict occurred in database "OneClickDB", table "dbo.branchTbl", column 'id'.
The statement has been terminated.
System.Data.SqlClient.SqlCommand+<>c.<ExecuteDbDataReaderAsync>b__122_0(Task<SqlDataReader> result)

DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)

Stack Query Cookies Headers
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ClintsTbl_branchTbl". The conflict occurred in database "OneClickDB", table "dbo.branchTbl", column 'id'. The statement has been terminated.
System.Data.SqlClient.SqlCommand+<>c.<ExecuteDbDataReaderAsync>b__122_0(Task<SqlDataReader> result)
System.Threading.Tasks.ContinuationResultTaskFromResultTask<TAntecedentResult, TResult>.InnerInvoke()
System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, object state)
System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref Task currentTaskSlot)
Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary<string, object> parameterValues, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)

Show raw exception details
System.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ClintsTbl_branchTbl". The conflict occurred in database "OneClickDB", table "dbo.branchTbl", column 'id'.
The statement has been terminated.
   at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__122_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
ClientConnectionId:5ea81819-1fa1-41b2-ba3a-1e8e66c0af3f
Error Number:547,State:0,Class:16
DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(DbContext _, ValueTuple<IEnumerable<ModificationCommandBatch>, IRelationalConnection> parameters, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync<TState, TResult>(TState state, Func<DbContext, TState, CancellationToken, Task<TResult>> operation, Func<DbContext, TState, CancellationToken, Task<ExecutionResult<TResult>>> verifySucceeded, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList<InternalEntityEntry> entriesToSave, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken)
OneClickAPI.Controllers.ClintsController.PostClintsTbl(ClintsTbl clintsTbl) in ClintsController.cs
+
            if (!ModelState.IsValid)
            
                return BadRequest(ModelState);
            
            _context.ClintsTbl.Add(clintsTbl);
            await _context.SaveChangesAsync();
            return CreatedAtAction("GetClintsTbl", new  id = clintsTbl.Id , clintsTbl);
        
        // DELETE: api/Clints/5
        [HttpDelete("id")]
Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Show raw exception details
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ClintsTbl_branchTbl". The conflict occurred in database "OneClickDB", table "dbo.branchTbl", column 'id'.
The statement has been terminated.
   at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__122_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(DbContext _, ValueTuple`2 parameters, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList`1 entriesToSave, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
   at OneClickAPI.Controllers.ClintsController.PostClintsTbl(ClintsTbl clintsTbl) in E:\my project\OneClickAPI\Controllers\ClintsController.cs:line 96
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
No QueryString data.

No cookie data.

Variable    Value
Accept  application/json, text/plain, */*
Accept-Encoding gzip, deflate, br
Accept-Language en-US,en;q=0.9,ar;q=0.8
Connection  Keep-Alive
Content-Length  97
Content-Type    application/json
Host    localhost:4200
MS-ASPNETCORE-TOKEN 669b781b-f87b-4a05-bf6c-5a88181a3530
Origin  http://localhost:4200
Referer http://localhost:4200/clients/clientInfo
sec-fetch-mode  cors
sec-fetch-site  same-origin
User-Agent  Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36
X-Original-For  127.0.0.1:10620
X-Original-Proto    http

【问题讨论】:

How to enable CORS in ASP.NET Core的可能重复 不幸的是,我尝试了所有这些但我仍然有同样的错误实际上我需要帮助 您需要显式调用app.UseExceptionHandler(...)。更多信息here. 【参考方案1】:

app.UseCors() 中间件应该在 app.UseMvc(); 中间件之前。

尝试切换顺序:

 app.UseCors("enableCors");
 app.UseMvc(); 

更新

对于开发,最推荐使用代理(angular-cli 自带)。

代理到后端服务器

您可以使用 webpack 开发服务器中的代理支持将某些 URL 转移到后端服务器,方法是将文件传递给 --proxy-config 构建选项。例如,要将所有对http://localhost:4200/api 的调用转移到在http://localhost:21063/api 上运行的服务器,请执行以下步骤。

第 1 步:

在项目的 src/ 文件夹中创建一个名为 proxy.conf.json 的文件..

第 2 步:

将以下内容添加到新创建的proxy.conf.json 文件中:


  "/api": 
    "target": "http://localhost:21063",
    "secure": false
  

第 3 步:

在 CLI 配置文件 angular.json 中,将 proxyConfig 选项添加到服务目标:

...
"architect": 
  "serve": 
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": 
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy.conf.json"
    ,
...

第 4 步:

编辑您的service.ts

export class ClientsService 

  clientsUrl="http://localhost:4200/api/clints"

  client:Clients;

第 5 步:

要使用此代理配置运行开发服务器,请致电 ng serve.

【讨论】:

首先非常感谢您的支持,我改了之后没有任何反应,还是一样的错误。 .Build(); 是干什么用的? 尝试省略它。 我很困惑,还是同样的错误,我的代码有什么错误或遗漏吗? 您是否尝试省略它?你在使用角度代理开发吗?

以上是关于为啥我收到 Cors 错误:...已被 CORS 政策阻止的主要内容,如果未能解决你的问题,请参考以下文章

为啥我在角度请求中收到此错误? (CORS)

即使我允许所有来源,为啥我会收到 CORS 错误?

CloudFront 已被 CORS 策略阻止

当 OPTIONS 请求的 statusCode 为 200 时,为啥我会在 API Gateway GET 请求中收到 CORS 错误?

已被 CORS 策略阻止:对预检请求的响应未通过

使用resttemplate访问时,如何使端点仅接受springboot中启用@crossorigin的uri?为啥我没有收到 cors 错误? [复制]