Home > Software engineering >  Why is my .Net Core app processing js files in script tags on .cshtml page as part of the react js a
Why is my .Net Core app processing js files in script tags on .cshtml page as part of the react js a

Time:12-09

We have an existing .Net Core 5 web app which we added a reactjs app to in order to start migrating portions of the site to react. It is working great with both sections of the site separated and running in harmony, EXCEPT....

When we load a regular .cshtml page the JavaScript files for the .Net Core web pages (.cshtml) are redirecting to the react app instead of loading the file to the page. Example: The homepage is https://mydomain-dot-com/ and it is a .Net Core .cshtml page. These js files are in script tags on the .cshtml page.

<script src="~/js/what-input.js"></script>
<script src="~/js/foundation.js"></script>
<script src="~/js/web-app.js"></script>

Each of these scripts are throwing the dreaded Unexpected token error which normally is thrown when the js file cannot be found.

   Uncaught SyntaxError: Unexpected token '<'

Upon further exploration, we found that the ~/js/what-input.js(etc.) is actually causing the reactjs app to load.

The url for the reactjs app is https://mydomain-dot-com/clientapp and should only load when we navigate to that url and when we do it works fine.

It seems like the reactjs app is treating ALL js files as react files and loading the react app.

Here is the startup.cs file and configurations so you can see how the SPA is implemented.

public class Startup
{


    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }


    public void ConfigureServices(IServiceCollection services)
    {


        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
         options =>
         {
             options.LoginPath = new PathString("/account/logon");
             options.AccessDeniedPath = new PathString("/account/denied");
             options.LogoutPath = new PathString("/");
             options.Cookie.HttpOnly = true; //added 11/10/2021 for reactjs app
         });

        services.ConfigureApplicationCookie(options =>
        {
            options.LoginPath = new PathString("/Account/Logon");
         
        });
        

        services.AddRazorPages().AddRazorRuntimeCompilation();
        services.AddControllersWithViews().AddRazorRuntimeCompilation();

        services.AddMemoryCache();
        services.AddAuthorization();
        services.AddControllers();


        services.Configure<AppSettings>(Configuration.GetSection(AppSettings.SectionName));
        services.AddOptions();


        services.AddSpaStaticFiles(configuration => {
            configuration.RootPath = "ClientApp/build";
        });

        services.AddCors(c =>
        {
            c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
        });

    }


    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsEnvironment("LocalDevelopment"))
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");

            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseDefaultFiles();
        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @".well-known")),
            RequestPath = new PathString("/.well-known"),
            ServeUnknownFileTypes = true // serve extensionless
   
        });

        app.UseSpaStaticFiles();

        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();


        app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                       name: "default",
                       pattern: "{controller=Home}/{action=Index}/{id?}");

        });


        app.UseSpa(spa => {
            spa.Options.SourcePath = "ClientApp";
            if (env.IsEnvironment("LocalDevelopment"))
            {
                spa.UseReactDevelopmentServer(npmScript: "start");
            }

        });


        AppDomain.CurrentDomain.SetData("ContentRootPath", env.ContentRootPath);
        AppDomain.CurrentDomain.SetData("WebRootPath", env.WebRootPath);


    }
}

The question is how do we prevent non-reactjs javascript files from redirecting to the app so that they behave as they should on the .cshtml page? Is there a way to explicitly separate these concerns so they act independently?

CodePudding user response:

I presume you would require an another middleware to serve content from wwwroot

app.UseStaticFiles();

example:

app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @".well-known")),
            RequestPath = new PathString("/.well-known"),
            ServeUnknownFileTypes = true
        });

services.AddSpaStaticFiles();
  • Related