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

穆罕默德·埃尔卡斯特

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

从源“ 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 获取数据的字符串东西,当我发布时发生了这个错误。

我的组件.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)
        })
    }
  }
...

服务.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”)。

错误对象 { headers: {…}, status: 0, statusText: "Unknown Error", url: " http://localhost:21063/api/clints ", ok: false, name: "HttpErrorResponse", message: "Http http://localhost:21063/api/clints 的失败响应:0 未知错误”,错误:错误 }。

更新

我的控制器.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
拉菲·赫尼格

app.UseCors()中间件应该先于app.UseMvc();中间件。

尝试切换顺序:

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


更新

对于开发,最推荐使用代理(随 angular-cli 一起提供)。

代理到后端服务器

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



第1步:

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

第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"
    },
...

第四步:

编辑您的 service.ts

export class ClientsService {

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

  client:Clients;

第 5 步:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

已被CORS政策阻止:对预检请求的响应未通过访问控制检查

Axios请求:被CORS政策阻止

已启用CORS,但仍收到CORS错误

Google OAuth2:重定向已被CORS政策阻止:请求需要进行预检,不允许遵循跨域重定向

对XMLHttpRequest的访问已被CORS策略阻止

Google Play商店无法上传带有“被CORS政策阻止”错误的应用程序图标

“重定向已被CORS策略阻止” Vue Axios

如何修复XMLHttpRequest已被CORS策略阻止

Blazor请求被CORS政策阻止

Vue。js CORS问题,后端数据被CORS政策阻止

CORS政策已被我的子域屏蔽

javascript:由于通配符而被CORS政策阻止

尝试使用axios访问Wikipedia Api,但收到CORS政策错误

空白cors政策阻止我在expressjs中的请求

仍然收到错误消息,已被CORS政策阻止

起源已被CORS策略阻止Spring引导和React

文件上传已被CORS政策阻止

Node.JS OvernightJS Express CORS XMLHttpRequest已被CORS策略阻止

为什么我会从 Google Cloud Functions 上不变的来源收到间歇性 CORS 错误?

WordPress 发布失败;javascript 显示错误“访问获取...已被 CORS 政策阻止”

向被 CORS 政策阻止的 API 发布请求

Post API 的问题:“已被 CORS 策略阻止......”

当我尝试使用 Axios 调用 Instagram API 时,我被“CORS 政策阻止”

“...已被 CORS 政策阻止:没有‘访问控制允许来源’”

Django Vue Js Axios 已被 CORS 政策阻止

从源“S3_host_url”获取“API_Gateway_URL”的访问已被 CORS 政策阻止

Angular Front - Cloud Functions 上的 NEST JS - 已被 CORS 政策阻止:没有“访问控制允许来源”

URL 已被 CORS 策略阻止

Stackexchange REST API 已被 CORS 政策阻止