Home > Net >  Cross-Origin Request Blocked even though it responds with 200 ok status code
Cross-Origin Request Blocked even though it responds with 200 ok status code

Time:12-19

Folks I'm developing a fullstack React.js - ASP.NET Core 5 application. The backend is done (fully tested). Of course it includes a CORS policy to allow request from the client side, but when I'm trying to send a request from react using axios, axios throws a network error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:5001/api/customers. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.

I see the server sends correct responses (I can even debugged the server) but axios stills failing. I only tried to solved it by including a proxy in package.json:

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

I'm going to include my app.js request code and startup.cs code, since it contains the CORS Policy:

Client

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

Server

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();
        });
    }
}


Edited: I'm including the CustomersController.cs code plus the details from the HTTP request.
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);
        }
}

Request image: enter image description here Any ideas, thoughts? I really need your help folks, this is a technical assignment for a dev job.

CodePudding user response:

Try to use the setting without the slash at the end: builder.WithOrigins("http://localhost:3000");

After the change please do a clean and rebuild the project, as it might be a thing.

Also, you don't need a proxy setting on the JS side.

P.S. A mode for the request might not be set properly on the Axios side. In case the solution above doesn't work try to use:

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

CodePudding user response:

Try to add this attribute to your controllers

[EnableCors(MyAllowSpecificOrigins)]
  • Related