简体   繁体   中英

React JS, ASP.Net core Web API handle Cors

My Project is having 2 apps. A React JS based SPA app and a ASP.Net Core web API project. The issue is I'm getting error "Referrer Policy: strict-origin-when-cross-origin"

I went through the articles on the web on how to allow Cors on the Web API project.But my question is this. Based on the recommended way of fixing this, is to define the set of allowed origins. But since front end is a JS app, the API request will come from the client or user's machine. So I can not exactly define the origin.

Other option is allow for all origins. Will this be be best option for my scenario? Or is there any other way of doing it.

A misunderstanding.

But since front end is a JS app, the API request will come from the client or user's machine.

API requests will definitely come from the client or user's machine but via your server where is the React application hosted.

So, your server is the origin.

Eg: When you are in the development phase, your React application will be hosted in say http://localhost:3000/ . This is the origin of the request.

Hence in the.Net Core project, CORS should be configured at Startup.cs as:

At ConfigureServices method:

services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder
                        .WithOrigins("http://localhost:3000/")
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());
            });

and at Configure method:

app.UseCors("CorsPolicy");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM