2

I have created an end point in csharp web api which returns some json data, it works fine on postman. but when I try the same url on my react app I get the following error

React code

fetch('https://localhost:44391/agency')
  .then(response => response.json())
  .then(json => console.log(json))

Error

Access to fetch at 'https://localhost:44391/agency' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I followed this link Trying to use fetch and pass in mode: no-cors and tried the following code

fetchData () {
           var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
    targetUrl = 'https://localhost:44391/agency'
fetch(proxyUrl + targetUrl)
        .then(blob => blob.json())
        .then(data => {
            console.log(data);
            return data;
        })
        .catch(e => {
            console.log(e);
            return e;
        });
      }

I get this error

GET https://cors-anywhere.herokuapp.com/https://localhost:44391/agency 404 (Not Found)
SyntaxError: Unexpected token N in JSON at position 0

Note The steps from the link which I could not do was

git clone https://github.com/Rob--W/cors-anywhere.git - DONE

cd cors-anywhere/ - DONE

npm install - DONE

heroku create - COULD NOT DO THIS. DO I NEED HEROKU, I AM NOT SURE WHY

git push heroku master - NOT DONE YET

Your help is much appreciated

Thanks P

Update

I have enabled CORS on my c# web api following the link https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#dp

section i followed was CORS with default policy and middleware

and my code is bellow

I have tried options.AddPolicy and options.AddDefaultPolicy but when I call from react app it still does not work

namespace React_NalONE_API
{
    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/*",
                //                                   "https://localhost/*");
                //         });

                options.AddDefaultPolicy(
                builder =>
                {
                    builder.WithOrigins("http://localhost/*",
                                        "https://localhost/*");
                });
            });
            services.AddControllers();
        }

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

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers().RequireCors(MyAllowSpecificOrigins);
            });
        }
    }
}
Auo
  • 399
  • 2
  • 5
  • 16
  • If the web API is on localhost, you can modify it by adding the proper headers from the API response. This particularly happens if your response to `OPTIONS` method is missing `Access-Control-Allow-Origin` where, the header value needs to be either `*` (if not using credentials) or the request origin (as specified by the request `Origin` header). – Abrar Hossain May 10 '20 at 11:37

1 Answers1

1

You don't need Heroku if you're just trying to test it locally. I'm assuming that bit on the tutorial you used was just to deploy the application, in order to demonstrate it's functionality. You don't necessarily need to follow through with that bit to get everything to work.

The issue seems to be with CORS permissions, usually browsers don't let you make CORS requests unless the response from the origin that you're requesting contains the right CORS headers. I would check this out for some more context.

If enabling CORS is something you're looking to do, then you probably want to enable CORS in .NET (I'm assuming that you're using .NET - whatever framework you're using, there should be a way to enable CORS)

Raghav
  • 470
  • 3
  • 13
  • Hi @Raghav thank you for replying, apologies for replying late, i did try what you suggested. Yes i have a c# web api which is on my local host. I followed your link and enabled cors on web api using `CORS with default policy and middleware`. i will update my question with the c# code. on react app i am calling without any proxy but still I get the same error, so is this issue on react or c# – Auo May 10 '20 at 22:12
  • Check this out? https://daveceddia.com/access-control-allow-origin-cors-errors-in-react-express/ – Raghav May 12 '20 at 06:00