Skip to content
This repository has been archived by the owner on Apr 8, 2020. It is now read-only.

Error when using HMR with ASP.NET CORE 2.0 #1204

Closed
praneethw opened this issue Aug 18, 2017 · 25 comments
Closed

Error when using HMR with ASP.NET CORE 2.0 #1204

praneethw opened this issue Aug 18, 2017 · 25 comments

Comments

@praneethw
Copy link

I have upgraded my solution to ASP.NET CORE 2.0, from 1.0 which was already configured for HMR. However after the upgrade I get the following error,

hrm_error

I can ofcource get rid of the error by setting HotModuleReplacement to false, however is there a fix to this such that I can continue to use SPA services with HMR?

The code for enabling HMR in my app is listed below,

app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions() { HotModuleReplacement = true });

@tonywr71
Copy link

I am also experiencing this problem.

What I have attempted to do is to add AspNetCore.Identity to the initial template application, so that I can use standard forms authentication with an Angular app.

When I first installed the Angular template, it was all working perfectly with hot module replacement.

After installing the Identity components, as per the Microsoft article "Introduction to Identity on ASP.NET Core" found here, the application is still all working, but the hot module replacement is failing, with the message: "EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection."

I can only assume that it is somehow interfering with the __webpack_hmr path.

Any idea how I can get this working?

I have put my application up on bitbucket here. I have disabled the Authorize attribute for now (it made no difference to HMR, it fails either way.)

(Note: If you want to get the Authorization working, after making sure the initial application runs, open up the package manager console and type Update-Database. To add a new account, go directly to the URL /Account/Register and add an email address and password. Then you should be able to uncomment the Authorize attribute in the HomeController and it will authorize. When you run the app, it will redirect to the login page and you can log in. It will then return to the Home Index page and will be authorized. )

@tonywr71
Copy link

Ok, I've taken a look at the Network tab, and the __webpack_hmr file is being requested but I believe it is falling back to the default route and not returning __webpack_hmr. I have attached an image of the network tab, showing the __weback_hmr request below. In the original generated code, it is requesting __webpack_hmr from the dist folder (http://localhost:53145/dist/__webpack_hmr), but after installing the identity components and setting https, it is trying to get it from the root folder (https://localhost:44396/__webpack_hmr.) Would anyone know where I configure this?

hmr-network-trace

@tonywr71
Copy link

tonywr71 commented Aug 19, 2017

I should add, when I go directly to /dist/__webpack_hmr on the initial angular template, it shows the following:
data: {"action":"sync","time":651,"hash":"4b36e9615bb959fb5f9b","warnings":[],"errors":[],"modules":{"0":"external \"vendor_4adf5b975b06d7f766a2\"","1":"delegated ./node_modules/@angular/core/@angular/core.es5.js from dll-reference vendor_4adf5b975b06d7f766a2","2":"./ClientApp/app/components/app/app.component.ts","3":"./~/css-loader/lib/css-base.js","4":"./~/html-entities/lib/html5-entities.js","5":"delegated ./node_modules/@angular/http/@angular/http.es5.js from dll-reference vendor_4adf5b975b06d7f766a2","6":"./ClientApp/boot.browser.ts","7":"(webpack)-hot-middleware/client.js?path=__webpack_hmr&dynamicPublicPath=true","8":"delegated ./node_modules/event-source-polyfill/eventsource.js from dll-reference vendor_4adf5b975b06d7f766a2","9":"./~/ansi-html/index.js","10":"./~/ansi-regex/index.js","11":"./ClientApp/app/app.module.browser.ts","12":"./ClientApp/app/app.module.shared.ts","13":"./ClientApp/app/components/counter/counter.component.ts","14":"./ClientApp/app/components/fetchdata/fetchdata.component.ts","15":"./ClientApp/app/components/home/home.component.ts","16":"./ClientApp/app/components/navmenu/navmenu.component.ts","17":"./~/css-loader!./ClientApp/app/components/app/app.component.css","18":"./~/css-loader!./ClientApp/app/components/navmenu/navmenu.component.css","19":"./~/html-entities/index.js","20":"./~/html-entities/lib/html4-entities.js","21":"./~/html-entities/lib/xml-entities.js","22":"./ClientApp/app/components/app/app.component.html","23":"./ClientApp/app/components/counter/counter.component.html","24":"./ClientApp/app/components/fetchdata/fetchdata.component.html","25":"./ClientApp/app/components/home/home.component.html","26":"./ClientApp/app/components/navmenu/navmenu.component.html","27":"./~/querystring-es3/decode.js","28":"./~/querystring-es3/encode.js","29":"./~/querystring-es3/index.js","30":"./~/reflect-metadata/Reflect.js","31":"./~/strip-ansi/index.js","32":"./ClientApp/app/components/app/app.component.css","33":"./ClientApp/app/components/navmenu/navmenu.component.css","34":"(webpack)-hot-middleware/client-overlay.js","35":"(webpack)-hot-middleware/process-update.js","36":"(webpack)/buildin/module.js","37":"delegated ./node_modules/process/browser.js from dll-reference vendor_4adf5b975b06d7f766a2","38":"delegated ./node_modules/@angular/forms/@angular/forms.es5.js from dll-reference vendor_4adf5b975b06d7f766a2","39":"delegated ./node_modules/@angular/platform-browser-dynamic/@angular/platform-browser-dynamic.es5.js from dll-reference vendor_4adf5b975b06d7f766a2","40":"delegated ./node_modules/@angular/router/@angular/router.es5.js from dll-reference vendor_4adf5b975b06d7f766a2","41":"delegated ./node_modules/bootstrap/dist/js/npm.js from dll-reference vendor_4adf5b975b06d7f766a2","42":"delegated ./node_modules/zone.js/dist/zone.js from dll-reference vendor_4adf5b975b06d7f766a2","43":"delegated ./node_modules/@angular/platform-browser/@angular/platform-browser.es5.js from dll-reference vendor_4adf5b975b06d7f766a2","44":"delegated ./node_modules/webpack/buildin/global.js from dll-reference vendor_4adf5b975b06d7f766a2","45":"delegated ./node_modules/@angular/common/@angular/common.es5.js from dll-reference vendor_4adf5b975b06d7f766a2","46":"multi event-source-polyfill webpack-hot-middleware/client?path=__webpack_hmr&dynamicPublicPath=true ./ClientApp/boot.browser.ts"}} data: 💓

but when I try to go to the same URL in the Identity version, it redirects to the home page. I suspect I need to handle the route separately.

@MarkPieszak
Copy link
Contributor

Yes that's what I've seen as well, I think the dotnet routing is taking over and trying to handle the request, returning text/html, so it's sending the actual webpack_hmr hot file.

MarkPieszak added a commit to TrilonIO/aspnetcore-angular-universal that referenced this issue Aug 19, 2017
Main goal is to re-align a bit more with JavaScriptServices to ensure
people coming from there, wanting to add additional features, have an
easier time syncing with this repo.

Adds back vendor builds,
Adds back fast HMR (but waiting for
aspnet/JavaScriptServices#1204)
AoT faster
Cleans up multiple tsconfigs
etc etc...
@tonywr71
Copy link

In the original, out of the box angular template, I do see an Event Stream tab when I look at the __webpack_hmr file under Network and it is responding with a type "text/event-stream". In the Identity version, it is returning text/html but I think this is because it is being routed to the home page. It can't get to the real __webpack_hmr file at all.

@tonywr71
Copy link

I have managed to get the application working properly with Identity and HMR by rebuilding the application again incrementally. So that's an Angular 4 app on AspNet Core 2.0 on Dot Net Framework 4.7 using HMR and including Identity. It is stripped right down, so it provides simple Login with an email address and password, and I have added a logout button to the navbar as well.

The Home controller has an Authorize attribute. If you aren't authorised, you will be redirected to Account/Login to log in to the site. There you can register an account, or if you have already registered one, log in. If the database hasn't been created for you, open up a package manager console and run Update-Database.

The only thing I haven't done is to validate the anti-forgery token on logging out. That's because the existing Anti Forgery token is Http only, so I can't actually get access to it in typescript on the client to be able to post back to the server. So for now, the ValidateAntiForgeryToken attribute is commented out in the Account controller Logout method.

I still haven't figured out why the other version of the app is not working.

My working example can be found on bitbucket [here].(https://bitbucket.org/tonywr7/genericangularwebapp)

@MaximBalaganskiy
Copy link

MaximBalaganskiy commented Aug 20, 2017

I solved this by adding an option

app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
				HotModuleReplacement = true,
				HotModuleReplacementEndpoint = "/dist/__webpack_hmr"
			});

Has something to do with https I think, because in the dotnet new aurelia over http HMR works just fine

@SteveSandersonMS
Copy link
Member

Glad you got this tracked down!

MarkPieszak added a commit to TrilonIO/aspnetcore-angular-universal that referenced this issue Aug 24, 2017
* WIP - Re-sync with JavaScriptServices

Main goal is to re-align a bit more with JavaScriptServices to ensure
people coming from there, wanting to add additional features, have an
easier time syncing with this repo.

Adds back vendor builds,
Adds back fast HMR (but waiting for
aspnet/JavaScriptServices#1204)
AoT faster
Cleans up multiple tsconfigs
etc etc...

* fix gitignore

* fix HMR, VS builds, misc updates

* add package-lock to gitignore

closes #307 
closes #318 
closes #296 
closes #294 
closes #271 
closes #267 
closes #230 
closes #161
@8enSmith
Copy link

@MaximBalaganskiy I'd looked everywhere for a solution to this issue and this code did the trick for me:

HotModuleReplacementEndpoint = "/dist/__webpack_hmr"

Great work!

GrandofDeveolop added a commit to GrandofDeveolop/angular-2-aspnet that referenced this issue Sep 21, 2017
* WIP - Re-sync with JavaScriptServices

Main goal is to re-align a bit more with JavaScriptServices to ensure
people coming from there, wanting to add additional features, have an
easier time syncing with this repo.

Adds back vendor builds,
Adds back fast HMR (but waiting for
aspnet/JavaScriptServices#1204)
AoT faster
Cleans up multiple tsconfigs
etc etc...

* fix gitignore

* fix HMR, VS builds, misc updates

* add package-lock to gitignore

closes #307 
closes #318 
closes #296 
closes #294 
closes #271 
closes #267 
closes #230 
closes #161
@ConductedClever
Copy link

A note for the people from future.
This setting has probably already been done. Be careful not to do it again.

I mean do not do my error:

..............
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true
            });
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

         app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true,
                HotModuleReplacementEndpoint = "/dist/__webpack_hmr"
            });
............

but do this:

.....
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true,
                HotModuleReplacementEndpoint = "/dist/__webpack_hmr"
            });
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
..............

@k11k2
Copy link

k11k2 commented Dec 12, 2017

@SteveSandersonMS I commented out this for some reasons. how do I over come above issue now?

//app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            //{
               // HotModuleReplacement = true
            //});

@tonywr71
Copy link

tonywr71 commented Dec 12, 2017 via email

@k11k2
Copy link

k11k2 commented Dec 13, 2017

@tonywr71 What about in production? where it ignores this part.

@tonywr71
Copy link

tonywr71 commented Dec 13, 2017 via email

@MaximBalaganskiy
Copy link

MaximBalaganskiy commented Dec 13, 2017

@AlwaysAbhl001 HMR in production? What for?

@k11k2
Copy link

k11k2 commented Dec 13, 2017

I commented HMR for some reasons in past. Added cookie authentication where it post back to callback controller to collect the token return a view. In such case for next call if user is already identified then returning Index view. This is my scenario where I'm facing this issue. And I'm looking for answer where I need not to touch the UseWebpackDevMiddleware part in startup.cs

@MaximBalaganskiy
Copy link

Not sure how UseWebpackDevMiddleware is related to auth.

@racjc
Copy link

racjc commented Dec 14, 2017

Hi,
I had the same issue and solve it by adding this lines in the configure method of the startup class :
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
ServeUnknownFileTypes=true
});
as __webpack_hmr is not a known file type the server doesn't server it without this line. :-)

@ghost
Copy link

ghost commented Jan 14, 2018

Hi, guys , I am using MPA (multiple SPA) which means one MVC view returns a SPA. The [EventSource's response has a MIME type ("text/html") that is not 'text/event-stream'. Aborting the connection.] issue still happens to me after trying the fix mentioned by @MaximBalaganskiy .

Any help would be appreciated,
Thanks,
Adrian

@racjc
Copy link

racjc commented Jan 15, 2018

Hi,
Perhaps doing something like that:
var provider = new FileExtensionContentTypeProvider();
// Add new mappings here if needed. the two lines above are for my own needs
provider.Mappings[".msg"] = "application/vnd.ms-outlook";
provider.Mappings[".properties"] = "text/x-java-properties";

        app.UseStaticFiles(new StaticFileOptions()
        {
            FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot")),
            
            RequestPath = new PathString(""),
            ContentTypeProvider = provider,
            ServeUnknownFileTypes=true
        });

This is the full code working for me.

@ghost
Copy link

ghost commented Jan 19, 2018

Hi, @racjc , I still have the same issue. Did yours combine with @MaximBalaganskiy solution ?
Should this path be the same for everyone HotModuleReplacementEndpoint = "/dist/__webpack_hmr" ?
My browser is loading the static file from the wwwroot directory in my project codebase.

@racjc
Copy link

racjc commented Jan 19, 2018

Hi, no. here is my hotmodule conf:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();

            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true,
                ConfigFile = "webpack.config.js",
            });
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

Did you set the publicPath in webpack.config.js file ?
I guess that __webpack_mr is not found and your system return a defined 404 not found error file which is "text/html" content.

@ghost
Copy link

ghost commented Jan 20, 2018

@racjc , I just realized that the <base href="@(string.Format("{0}://{1}{2}", Context.Request.Scheme, Context.Request.Host, Context.Request.Path))"> in the_Layout.cshtml causing the "EventSource's response" issue. So when I changed to href="~/" then this EventSource's error is gone. But my multiple SPA will not work. So what do you set for your base tag in html for MPA then?

Thanks,

@racjc
Copy link

racjc commented Jan 20, 2018

Hi,
@AdrianNg, I just put the application path as you define it in IIS. For instance if your path is http://mydomain/application/view in the _Layout.cshtml you just have to put href="/application/"
And in the startup.cs file you have to defines routes in the Configure method. Something like that:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "Views/{controller=Home}/{action=Index}.html/{id?}");
routes.MapRoute(
name: "api",
template: "api/{controller}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
As I use cshtml file in Angular component as template, i insert the ".html" in the route template so the correct link will be done. For instance :
@component({
selector: "import-initial",
templateUrl: "/application/Views/Partial/importinitial.html",
styles: [require("./importinitial.component.css")]
})
And in my webpack.config.js:
module: {
rules: [
{ test: /.ts$/, use: ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader']},
{ test: /.html$/, use: 'html-loader?minimize=false' },
{ test: /.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] },
{ test: /.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' },
...sharedModuleRules
]
},

@Dragon38
Copy link

npm install angular-router-loader --save-dev

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

10 participants