skip to Main Content

When I do axios post by React JS, I get the following CORS error to ASP.Net Core side.

Failed to load resource: Origin http://localhost:3000 is not allowed
by Access-Control-Allow-Origin.
https://localhost:5001/api/vendorregistration

I installed the following as my Nuget Packages and did not apply any other form below but it didn’t work.

  • Microsoft.AspNet.Cors. 5.2.7 Version
  • Microsoft.AspNetCore.Cors 2.1.1 Version

How to enable Cors for every type of request in asp.net core 3.1

Startup.cs

public class Startup
{
    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.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddCors(o => o.AddPolicy("ReactPolicy", builder =>
        {
            builder.AllowAnyHeader()
                   .AllowAnyMethod()
                   .AllowAnyOrigin();
               //    .AllowCredentials();
        }));

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // 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();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseHttpsRedirection();

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

    }
}

VendorRegistrationController.cs

namespace Bait.Controllers
{

[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
[EnableCors("ReactPolicy")]

ReactJS Side RegistrationForm.tsx

 const handleFormSubmit = async (values: any): Promise<any> => {
   const response = await axios.post<User>('https://localhost:5001/api/vendorregistration', { data: values })
   console.log(response);
 };

2

Answers


  1. you do not have to use in every actions in the controller. just put app.UseCors("ReactPolicy"); line before app.UseStaticFiles(); line

    app.UseCors("ReactPolicy");
    

    Hope it’ll work!

    Login or Signup to reply.
  2. Could you pls check my code snippet as it worked for me. I copied your startup file so I just put the using packages here.

    My test controller:

    using Microsoft.AspNetCore.Cors;
    using Microsoft.AspNetCore.Mvc;
    
    namespace WebAppMVCcore2.Controllers
    {
        [Produces("application/json")]
        [Route("api/[controller]")]
        [ApiController]
        [EnableCors("ReactPolicy")]
        public class HelloController : Controller
        {
        
            [HttpPost]
            public string Index()
            {
                return "hello";
            }
        }
    }
    

    And my startup file:

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    
    namespace WebAppMVC_core2
    {}
    

    And my test react code:

    import logo from './logo.svg';
    import './App.css';
    import React, { Component } from 'react';
    import axios from 'axios';
    
    class App extends Component {
    
      constructor(props){
        super(props);
      }
    
      componentDidMount(){
          const response = axios.post('https://localhost:44326/api/hello').then(res=>{
            console.log('res=>',res);            
          })
          console.log(response);
      }
      
      render() {
        return (
          <div className="App">
            <header className="App-header">
              <img src={logo} className="App-logo" alt="logo" />
              <p>
                Edit <code>src/App.js</code> and save to reload.
              </p>
              <a
                className="App-link"
                href="https://reactjs.org"
                target="_blank"
                rel="noopener noreferrer"
              >
                Learn React
              </a>
            </header>
          </div>
        );
      }
    }
    
    export default App;
    

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search