angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

Integrating angular2 Universal with angular CLI project

Open vinodbhargava opened this issue 10 years ago • 214 comments

  1. OS - Windows 8

  2. Versions - angular-cli: 1.0.0-beta.5 node: 4.3.1 os: win32 x64

  3. Yes, the app was created using CLI

  4. Steps - A. Created the app using following command - ng new testApp

    B. Installed angular2-universal dependencies as mentioned in -
    Angular 2 Universal quickstart

    C. Deployed client using command - ng server (server started on port 4200) Started express server through - node server.js (server started on port 3000)

    D. Accessed the client and got following message in browser - test-app works! But when accessing http://localhost:3000 it gives below error message in console -

EXCEPTION: Error: Protocol "d:" not supported. Expected "http:". STACKTRACE: Error: Protocol "d:" not supported. Expected "http:". at new ClientRequest (_http_client.js:52:11) at Object.exports.request (http.js:31:10) at Object.exports.get (http.js:35:21) at D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\angular2-universal\dist\node\platform\node_xhr_impl.js:53:22 at ZoneDelegate.invoke (D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\zone.js\dist\zone-node.js:281:29) at Object.NgZoneImpl.inner.inner.fork.onInvoke (D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\@angular\core\src\zone\ng_zone_impl.js:45:41) at ZoneDelegate.invoke (D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\zone.js\dist\zone-node.js:280:35) at Zone.run (D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\zone.js\dist\zone-node.js:174:44) at NgZoneImpl.runInner (D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\@angular\core\src\zone\ng_zone_impl.js:76:71) at NgZone.run (D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\@angular\core\src\zone\ng_zone.js:223:66) D:\Development\Angular2\angular-cli\cli-angular\testApp\node_modules\@angular\core\src\application_ref.js:302 throw e; ^

Kindly suggest if i had missed any step.

Any help will be appeciated.

vinodbhargava avatar Jun 09 '16 08:06 vinodbhargava

@Toxicable , I am in client and have two folders following https://github.com/angular/angular-cli/wiki/stories-universal-rendering. Is there a way to test dist-server locally?

ennyta avatar Sep 11 '17 01:09 ennyta

@ennyta are you planning on doing prerendering or using Express/aspnetcore to do dynamic rendering?

Toxicable avatar Sep 11 '17 01:09 Toxicable

@Toxicable Trying to do prerendering, managed to run it and now getting error like this: import { Injectable } from '@angular/core'; ^^^^^^ SyntaxError: Unexpected token import at createScript (vm.js:53:10) at Object.runInThisContext (vm.js:95:10) at Module._compile (module.js:543:28) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3) at Module.require (module.js:498:17) at require (internal/module.js:20:19) at Object.sZvN (C:\Users\ana\workspace\foodfest\foodfest-client-cli\dist-server\main.ed8dace87ce02020841a.bundle.js:1:859271)

Any idea if it is fixable? I see several people in this topic run into them, but I don't see if there is a solution for it.

ennyta avatar Sep 11 '17 12:09 ennyta

@ennyta the cli probably needs to include nodeExternals and whitelist angular modules that way webpack can read the es6 module syntax

Tipe CMS

PatrickJS avatar Sep 11 '17 16:09 PatrickJS

This seems to have been removed: https://github.com/Toxicable/universal-starter/tree/cli (I get a 404). I guess we can use the universal-starter/cli - it was updated like 10 days ago - but there are quite a few differences in the server.js and prerender.js files (compared to what @Toxicable 's repo had) - and maybe other files I haven't checked yet (I think I can say that, to me, they're almost like plain "text" differences, because I have no clue about Node development whatsoever). Should we consider that the CLI folder in the universal-starter is (and will continue be) the most up-to-date example of Universal implementation on a CLI generated app?

@gdi2290 About prerendering, I've read that "it renders your application and replaces the dist index.html with a rendered version.". What is that useful for? I mean, we don't only have a root (home) page. Should we manually go over all the routes and generate a static html file for each possible route? And is this done by simply replacing the value of the url key in the renderModuleFactory options? But, even so... we might have dynamic routes or route params and query params, which would be very difficult (if not impossible) to take into account in the prerender.js script to generate all possible html content files for all the possible routes/route params/query params combinations (not to mention that, for the route params, the actual values will most probably come from a database). I'm completely failing to understand what prerendering is about... I must be missing something, I guess it must have it's use... I think that I'm just failing to see what that is? If not, then it seems to be an overkill to implement. The way to go would then be dynamic and I'm sure that a Node developer would also be able to easily cache whatever content is generated on the first request and use that for future requests.

EDIT: Alright, so I've got my answer below. I understand that prerendering is more suitable for apps in which generating the content doesn't rely heavily on dynamic params (which most probably correspond with identifiers in some sort of server-side database). And for that, we're better off with dynamic rendering (and some sort of caching, of course). Thank you @Toxicable

NgxDev avatar Sep 15 '17 21:09 NgxDev

@ennyta See this issue for for information on that issue https://github.com/angular/angular-cli/issues/7200

@MrCroft My demo has been merged into https://github.com/angular/universal-starter/tree/master/cli The example there shows only the / route being rendered but I have a tool in the works that will allow you to dynamically generate prerenders for every static route in your app see: https://github.com/angular/universal/pull/778 or https://github.com/Toxicable/universal/tree/routes-ls for more about that. As for dynamic routes with params, they cannot be easily prerendered, you'd be best using one of the dynamic rendering engines we have, either the Node one for aspnetcore one, which will render your app on the fly meaning it can use all the params that come along with the request

Toxicable avatar Sep 15 '17 21:09 Toxicable

@MarkPieszak

As for cookies, in the server you'd have to handle it yourself by passing in the req object to the providers[] and then use Dependency injection to have the server use those, while the client gets them from document.cookies.

Since your comment, I've been searching back and forth for an actual example, but couldn't find one. So, I've blindly managed to do it after reading different issues/browsing through different repos, with this in my app.server.module.ts file:

// ...
import { Request } from 'express';
import { REQUEST } from '@nguniversal/express-engine/tokens';

export class RequestCookies {
    constructor(@Inject(REQUEST) private request: Request) {}

    get cookies() {
        return !!this.request.headers.cookie ? this.request.headers.cookie : null;
    }
}

@NgModule({
    imports: [
        // ...
    ],
    providers: [
        MyCustomCookieService,
        { provide: 'req', useClass: RequestCookies }
    ],
    bootstrap: [AppComponent]
})
export class AppServerModule {}

While also providing a dummy { provide: 'req', useValue: null } in my app.module.ts (that runs in the browser). Then, in my MyCustomCookieService I inject this: @Inject('req') private readonly req: any and simply check, if it's null then I use document.cookie, else I use req.cookies.

It does work, but I have to ask: is this exactly what you had in mind? Am I doing it the right way? Also, should I be comfortable with importing something from express in my Angular code?

Also, right now you can manually create or use one of the TransferHttp examples we have

~~Where can I find such an example? And/or some documentation to help me understand how to accomplish that? I think this would be the last thing needed for me to suggest going away from php and go for Node/Angular on a project that is planned for a complete rewrite anyway :)~~ So, since 5.0.0-rc.0 (if I'm not mistaking), TransferState comes with Angular.

NgxDev avatar Sep 16 '17 20:09 NgxDev

Regarding https://github.com/angular/angular-cli/issues/1050#issuecomment-328584662 by @gdi2290:

 the cli probably needs to include nodeExternals and whitelist angular modules that way webpack can read the es6 module syntax

I have experienced the same issue when trying to use ng-bootstrap on with universal.

Does anyone know if there is an open issue for the above (I can't seem to find one)? @hansl / @filipesilva ... if there isn't one, should there be?

somombo avatar Sep 25 '17 15:09 somombo

Can be closed since the CLI does work with Universal https://github.com/angular/angular-cli/wiki/stories-universal-rendering

Toxicable avatar Oct 17 '17 03:10 Toxicable

@MrCroft nicely done, yes that's a great way to get it! Yeah you're fine, you could also just do your own interface for it since you know the exact pieces you want. Either way is fine, since this is all in the server render anyway! 👍

MarkPieszak avatar Oct 18 '17 11:10 MarkPieszak

@somombo I am experiencing the issue to use ng-bootstrap on with universal. An open issue is here https://github.com/ng-bootstrap/ng-bootstrap/issues/858

Let me know if you found a way out of it!

itstyro avatar Oct 21 '17 09:10 itstyro

@itstyro I "fixed" my issue by basically not using ng-bootstrap i.e. forked their bit of code that i needed, and incorporated that directly into my project.. lol

Yeah, apart from the node externals outlined above, I'm still finding a variety of problems with the way angular-cli builds the server aspect of the project.

For example in my main.server.ts, I apparently cannot have access to the __dirname global variable.. I use process.cwd() instead but they are actually not exactly the same thing.

Also in the main.server.ts there is an error if you do not export the AppServerModule ... I dont want to have to do this because I use my main.server.ts file as the file where I invoke the renderModuleFactory() function.. not in a seperate server.ts as is suggested in the universal cli story.

somombo avatar Oct 22 '17 08:10 somombo

Closing as @Toxicable correctly mentioned CLI does work with Universal.

alan-agius4 avatar Oct 16 '18 12:10 alan-agius4

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.