【问题标题】:Cross-Origin Request Blocked even though it responds with 200 ok status code跨域请求被阻止,即使它以 200 ok 状态码响应
【发布时间】:2022-01-21 10:57:20
【问题描述】:

伙计们,我正在开发一个全栈 React.js - ASP.NET Core 5 应用程序。后端已完成(经过全面测试)。当然它包含一个 CORS 策略来允许来自客户端的请求,但是当我尝试使用 axios 从 react 发送请求时,axios 会引发网络错误:

跨源请求被阻止:同源策略不允许读取位于 https://localhost:5001/api/customers 的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)。状态码:200。

我看到服务器发送了正确的响应(我什至可以调试服务器)但 axios 仍然失败。我只是尝试通过在package.json 中包含代理来解决它:

"proxy": "https://localhost:5001"

我将包含我的 app.js 请求代码和 startup.cs 代码,因为它包含 CORS 政策:

客户

  const fetchCustomers = async () => {
    const customers = await axios.get(customersApiUrl);
    console.log(customers);
    setCustomers(customers);
    setIsLoading(false);
  };

服务器

public class Startup
{
    readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: MyAllowSpecificOrigins,
                              builder =>
                              {
                                  builder.WithOrigins("http://localhost:3000/");
                                  builder.AllowAnyHeader();
                                  builder.AllowAnyMethod();
                              });
        });
        services.AddControllers();
        services.AddDbContextPool<TwinEnginesDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("Standard")));
        services.AddScoped<ICustomerTypeRepository, CustomerTypeRepository>();
        services.AddScoped<ICustomerTypeService, CustomerTypeService>();
        services.AddScoped<ICustomerRepository, CustomerRepository>();
        services.AddScoped<ICustomerService, CustomerService>();
        services.AddAutoMapper(Assembly.GetExecutingAssembly());
    }

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

        app.UseHttpsRedirection();
        app.UseRouting();

        app.UseCors(MyAllowSpecificOrigins);
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}


已编辑:我包含了 CustomersController.cs 代码以及来自 HTTP 请求的详细信息。
CustomersController.cs

    [Route("api/[controller]")]
    [ApiController]
    public class CustomersController : ControllerBase
    {
        private readonly ICustomerService _customerService;
        private readonly ICustomerTypeService _typeService;
        private readonly IMapper _mapper;

        public CustomersController(ICustomerService customerService, ICustomerTypeService typeService, IMapper mapper)
        {
            this._customerService = customerService ?? throw new ArgumentNullException(nameof(customerService));
            this._typeService = typeService ?? throw new ArgumentNullException(nameof(typeService));
            this._mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        }

        // [EnableCors("MyAllowSpecificOrigins")]
        [HttpGet("")]
        public async Task<ActionResult<IEnumerable<CustomerDTO>>> GetCustomers()
        {
            var customers = await _customerService.GetAllAsync();
            var response = _mapper.Map<IEnumerable<CustomerDTO>>(customers);
            return Ok(response);
        }
}

请求图片: 有什么想法、想法吗?我真的需要你们的帮助,这是开发工作的技术任务。

【问题讨论】:

  • 标题中不要使用大写字母,被认为是大喊大叫,通常不受欢迎。

标签: reactjs asp.net-core asp.net-core-5.0


【解决方案1】:

尝试使用没有 斜线结尾:builder.WithOrigins("http://localhost:3000");

更改后请清理并重建项目,因为它可能是一个东西。

另外,你不需要在 JS 端设置代理。

附:请求的 mode 在 Axios 端可能未正确设置。如果上述解决方案不起作用,请尝试使用:

axios(requestURL, { mode: 'cors' })

【讨论】:

    【解决方案2】:

    尝试将此属性添加到您的控制器中

    [EnableCors(MyAllowSpecificOrigins)]
    

    【讨论】:

    • 我仍然遇到同样的错误
    • 你安装了Microsoft.AspNetCore.Cors 包吗?另外,请尝试使用相同的答案,但不要在 MyAllowSpecificOrigins 中使用引号,因为我意识到您使用的是变量而不是字符串。
    • 我认为 Microsoft.AspNetCore.Cors 已经附带了 asp.net core5,因为我没有任何错误,并且文档没有说明任何与安装它作为 CORS 的必要条件有关的内容。
    • 我添加了[EnableCors("_myAllowSpecificOrigins")],_myAllowSpecificOrigins 代表我的策略名称。
    猜你喜欢
    • 1970-01-01
    • 2021-06-26
    • 2014-10-13
    • 1970-01-01
    • 2018-06-13
    • 2019-11-04
    • 2017-02-06
    相关资源
    最近更新 更多