Adding CORS to our backend

We are going to try our real-time API now and discover a problem with it because the frontend is hosted in a different origin from the backend. Let's carry out the following steps to expose this problem and then correct it:

  1. Run the backend project by pressing F5 in Visual Studio.
  2. Run the frontend project by entering npm start in the Terminal in Visual Studio Code.
  3. When the frontend app runs, press F12 to open the browser DevTools and select the Console panel.
  4. Click on a question to open the question page. This is where the SignalR connection should be started and the client can subscribe to the question. We get an error, though:

The request to start the SignalR connection has been blocked by a CORS policy. 

CORS stands for Cross-Origin Resource Sharing and is a mechanism that uses HTTP headers to tell a browser to let a web application run at certain origins (domains) so that it has permission to access certain resources on a server at a different origin.

So, we need to configure our ASP.NET backend to allow requests from our React frontend because they are hosted in different origins.

  1. Stop the backend from running by pressing SHIFT+F5 in Visual Studio Code and enter the following statement inside the ConfigureServices method in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors(options =>
options.AddPolicy("CorsPolicy",
builder =>
builder.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("http://localhost:3000")
.AllowCredentials()));


services.AddSignalR();
}

This has defined a CORS policy that allows our frontend app hosted in the localhost:3000 origin to access the backend. If the origin of your frontend app is different, then simply change the origin in this statement as required.

  1. Now, we can enable the use of this policy in the Configure method. Let's add the following statement as the first statement in the Configure method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("CorsPolicy");

...
}
  1. Run the backend project again by pressing F5.
  2. If we hit F5 to refresh the frontend app, we'll see that it now connects to the SignalR server and subscribes to the question:

That's great!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.253.76