If you separate front and back end, you may have CORS issue. The CORS issue can happen if you assign different ports or use different domain.
This example shows how to add CORS to open a service to ALL external addresses to simplify the code. In any production environment, this is NOT a safe option. You must use CORS policy to allow only certain number of external addresses.
Before starting this, please make sure that you have gRPC-Web server feature already added to your gRPC service project.
Add the following lines of codes to Program.cs file.
builder.Services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyOrigin() //this is where it opens to ALL origin. You must use WithOrigin() in a production enviroment
.AllowAnyMethod()
.AllowAnyHeader()
.WithExposedHeaders("Grpc-Status", "Grpc-Message", "Grpc-Encoding", "Grpc-Accept-Encoding");
}));
Then add the following lines of codes (in the app section of Program.cs):
app.UseRouting();
app.UseGrpcWeb();
// Add the following line BELOW UseGrpcWeb()
app.UseCors();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<GreeterService>()
.EnableGrpcWeb()
// You are adding this line. "AllowAll" is the name of CORS policy you configured above
.RequireCors("AllowAll");
});
Congrats! You are all set.