Universal: Universal App fails on http://localhost:4200 but works on http://localhost:4200/index.html

Created on 19 Apr 2018  路  18Comments  路  Source: angular/universal

Note: for support questions, please use one of these channels. This repository's issues are reserved
for feature requests and bug reports. Also, Preboot has moved here - please make preboot-related issues
there.

  • I'm submitting a ...
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support request here, see note at the top of this template.
  • What modules are related to this Issue?
- [ ] aspnetcore-engine
- [ ] common
- [x] express-engine
- [ ] hapi-engine
- [ ] module-map-ngfactory-loader
  • What is the current behavior?

I followed the instructions on the angular-cli wiki to use universal, all compiled correctly with no errors.

The Universal App fails on http://localhost:4200 the first time it loads but works on http://localhost:4200/index.html

It works fine if I just run a http-server on client folder.

After loading http://localhost:4200/index.html the first time, then http://localhost:4200 is accessible.

The error I receive is 500 with a response of :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Error</pre>
</body>
</html>

Which seems to be a server error.

  • Please tell us about your environment:
  "dependencies": {
    "@amcharts/amcharts3-angular": "^2.0.3",
    "@angular/animations": "5.2.10",
    "@angular/cdk": "5.2.3",
    "@angular/common": "5.2.10",
    "@angular/compiler": "5.2.10",
    "@angular/core": "5.2.10",
    "@angular/forms": "5.2.10",
    "@angular/http": "5.2.10",
    "@angular/material": "5.2.3",
    "@angular/platform-browser": "5.2.10",
    "@angular/platform-browser-dynamic": "5.2.10",
    "@angular/platform-server": "5.2.10",
    "@angular/router": "5.2.10",
    "@angular/service-worker": "5.2.10",
    "@ngrx/effects": "5.1.0",
    "@ngrx/router-store": "5.0.1",
    "@ngrx/store": "5.1.0",
    "@ngrx/store-devtools": "5.1.0",
    "@nguniversal/express-engine": "^5.0.0",
    "@nguniversal/module-map-ngfactory-loader": "^5.0.0",
    "@ngx-share/buttons": "^5.0.0-beta.3",
    "@ngx-share/core": "^5.0.0-beta.3",
    "@nrwl/nx": "0.8.0",
    "@swimlane/ngx-datatable": "^11.1.5",
    "@toverux/ngx-sweetalert2": "^3.0.1",
    "amcharts3": "github:amcharts/amcharts3",
    "angular2-jwt": "^0.2.3",
    "classlist.js": "^1.1.20150312",
    "core-js": "^2.4.1",
    "google-libphonenumber": "^3.0.9",
    "lodash": "^4.17.4",
    "ng2-cookies": "^1.0.12",
    "ng2-pagination": "^2.0.1",
    "ngx-chips": "^1.6.1",
    "ngx-clipboard": "9.1.3",
    "ngx-order-pipe": "^2.0.1",
    "ngx-toastr": "^8.3.2",
    "ngx-uploader": "^4.2.4",
    "papaparse": "^4.3.6",
    "query-string": "^5.1.0",
    "raven-js": "^3.24.2",
    "rxjs": "^5.5.10",
    "socket.io-client": "^2.0.4",
    "sweetalert2": "^7.0.6",
    "tm-intro.js": "^2.9.0-alpha.1",
    "vis": "^4.21.0",
    "web-animations-js": "^2.3.1",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/core": "0.5.7",
    "@angular-devkit/schematics": "0.5.7",
    "@angular/cli": "1.7.4",
    "@angular/compiler-cli": "5.2.10",
    "@angular/language-service": "5.2.10",
    "@nrwl/schematics": "0.8.0",
    "@types/intro.js": "^2.4.3",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "@types/vis": "^4.21.0",
    "codelyzer": "~3.1.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "ngrx-store-freeze": "^0.2.0",
    "npm-run-all": "^4.1.2",
    "prettier": "1.10.2",
    "protractor": "~5.1.2",
    "ts-loader": "^3.5.0",
    "ts-node": "~3.2.0",
    "tslint": "~5.3.2",
    "typescript": "2.6.2",
    "webpack-node-externals": "^1.6.0"
  }
  • Other information (e.g. detailed explanation, stacktraces, related issues, suggestions how to fix, links for us
    to have context, eg. stackoverflow, gitter, etc)
express-engine hours

Most helpful comment

@RicardoVaranda , could you resolve this issue before?
I noticed that the express server was not serving index.html simply.
Please use res.sendFile() , instead ofres.render()

All 18 comments

Additional info:

server.ts:

// These are important and needed before anything else
import 'zone.js/dist/zone-node';
import 'reflect-metadata';

import { renderModuleFactory } from '@angular/platform-server';
import { enableProdMode } from '@angular/core';
import { ngExpressEngine } from '@nguniversal/express-engine';

import * as express from 'express';
import { join } from 'path';
import { readFileSync } from 'fs';

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express server
const app = express();

const PORT = process.env.PORT || 80;
const DIST_FOLDER = join(process.cwd(), 'dist/apps/trial-cloud');

// Our index.html we'll use as our template
const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/apps/trial-cloud/server/main.bundle');

const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader');

app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req });
});

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node server listening on http://localhost:${PORT}`);
});

webpack.server.config.js:

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: {  server: './tc-server.ts' },
  resolve: { extensions: ['.js', '.ts'] },
  target: 'node',
  // this makes sure we include node_modules and other 3rd party libraries
  externals: [/(node_modules|main\..*\.js)/],
  output: {
    path: path.join(__dirname, 'dist/apps/trial-cloud/'),
    filename: '[name].js',
    libraryTarget: 'commonjs2'
  },
  module: {
    rules: [
      { test: /\.ts$/, loader: 'ts-loader' }
    ]
  },
  plugins: [
    // Temporary Fix for issue: https://github.com/angular/angular/issues/11580
    // for "WARNING Critical dependency: the request of a dependency is an expression"
    new webpack.ContextReplacementPlugin(
      /(.+)?angular(\\|\/)core(.+)?/,
      path.join(__dirname, 'src'), // location of your src
      {} // a map of your routes
    ),
    new webpack.ContextReplacementPlugin(
      /(.+)?express(\\|\/)(.+)?/,
      path.join(__dirname, 'src'),
      {}
    )
  ]
}

Same here, it throws me Cannot read property 'originalUrl' of undefined presumably coming from https://github.com/angular/universal/blob/master/modules/express-engine/src/main.ts#L87 judging by stacktrace, index.html works fine for sure

At least you get an error stack, this is what we get:

ERROR [Error]
ERROR { Error: Uncaught (in promise): Error
    at resolvePromise (/Users/ricardo_varanda/Projects/product-cloud/dist/apps/trial-cloud/server.js:165901:31)
    at resolvePromise (/Users/ricardo_varanda/Projects/product-cloud/dist/apps/trial-cloud/server.js:165858:17)
    at /Users/ricardo_varanda/Projects/product-cloud/dist/apps/trial-cloud/server.js:165960:17
    at ZoneDelegate.invokeTask (/Users/ricardo_varanda/Projects/product-cloud/dist/apps/trial-cloud/server.js:165508:31)
    at Object.onInvokeTask (/Users/ricardo_varanda/Projects/product-cloud/dist/apps/trial-cloud/server.js:5246:33)
    at ZoneDelegate.invokeTask (/Users/ricardo_varanda/Projects/product-cloud/dist/apps/trial-cloud/server.js:165507:36)
    at Zone.runTask (/Users/ricardo_varanda/Projects/product-cloud/dist/apps/trial-cloud/server.js:165275:47)
    at drainMicroTaskQueue (/Users/ricardo_varanda/Projects/product-cloud/dist/apps/trial-cloud/server.js:165682:35)
    at ZoneTask.invokeTask (/Users/ricardo_varanda/Projects/product-cloud/dist/apps/trial-cloud/server.js:165587:21)
    at Server.ZoneTask.invoke (/Users/ricardo_varanda/Projects/product-cloud/dist/apps/trial-cloud/server.js:165572:48)
  rejection: [Error],
  promise: ZoneAwarePromise { __zone_symbol__state: 0, __zone_symbol__value: [Error] },
  zone:
   Zone {
     _properties: { isAngularZone: true },
     _parent:
      Zone {
        _properties: {},
        _parent: null,
        _name: '<root>',
        _zoneDelegate: [ZoneDelegate] },
     _name: 'angular',
     _zoneDelegate:
      ZoneDelegate {
        _taskCounts: [Object],
        zone: [Circular],
        _parentDelegate: [ZoneDelegate],
        _forkZS: null,
        _forkDlgt: null,
        _forkCurrZone: [Zone],
        _interceptZS: null,
        _interceptDlgt: null,
        _interceptCurrZone: [Zone],
        _invokeZS: [Object],
        _invokeDlgt: [ZoneDelegate],
        _invokeCurrZone: [Circular],
        _handleErrorZS: [Object],
        _handleErrorDlgt: [ZoneDelegate],
        _handleErrorCurrZone: [Circular],
        _scheduleTaskZS: [Object],
        _scheduleTaskDlgt: [ZoneDelegate],
        _scheduleTaskCurrZone: [Circular],
        _invokeTaskZS: [Object],
        _invokeTaskDlgt: [ZoneDelegate],
        _invokeTaskCurrZone: [Circular],
        _cancelTaskZS: [Object],
        _cancelTaskDlgt: [ZoneDelegate],
        _cancelTaskCurrZone: [Circular],
        _hasTaskZS: [Object],
        _hasTaskDlgt: [ZoneDelegate],
        _hasTaskDlgtOwner: [Circular],
        _hasTaskCurrZone: [Circular] } },
  task:
   ZoneTask {
     _zone:
      Zone {
        _properties: [Object],
        _parent: [Zone],
        _name: 'angular',
        _zoneDelegate: [ZoneDelegate] },
     runCount: 0,
     _zoneDelegates: null,
     _state: 'notScheduled',
     type: 'microTask',
     source: 'Promise.then',
     data: ZoneAwarePromise { __zone_symbol__state: 0, __zone_symbol__value: [Error] },
     scheduleFn: undefined,
     cancelFn: null,
     callback: [Function],
     invoke: [Function] } }
Error

@RicardoVaranda Are you sure, looking at server.js:165901:31, that this chunk is from @angular/universal package?

it also works only with index.html in my case. http://localhost:4200 gives error without any explanation

You likely just need configuration for a fallback route.
However this could be added to our starter, thanks for reporting this.

@Toxicable If problem not in universal, then what do exactly developers should do to fix it?

@VagrantAI-c as I explained above a the solution is likely to add a fallback route to the express server.
I don't know the exact syntax off the top of my head so cant give an example.

You can switch from express engine to hapiness engine and all documentation is here

A bit late but this might help some people that stumble upon this problem, I had the same exact error as above, and after few days of digging, I found the issue for me to be:
app.get('*', (request: Request, response: Response) => { response.render('index', {request}); });
to:
app.get('*', (req: Request, res: Response) => { res.render('index', {req}); });

(Using the abbreviated names of req and res instead of full name request and response).

My guess is that req is being passed somehow with the name of the property, and when accessed it is object.req, so if request is used instead, it doesn't find the object and ends up with undefined.

Literally just swapping the names from request to req solved my issue.

Cheers, good luck.

I'm getting ReferenceError: XMLHttpRequest is not defined
And my HttpClientModule is only being imported in app.module.ts
I can access the home page by going to localhost:8080/index.html but not just by localhost:8080
Overall universal routing is not working, instead express is just serving the index.html page as a static file.

Fixed: one of the modules was not compatible with angular universal (socket.io in my case). Just removed it.
Universal worked. The issue can be closed.

@RicardoVaranda , could you resolve this issue before?
I noticed that the express server was not serving index.html simply.
Please use res.sendFile() , instead ofres.render()

Fixed: one of the modules was not compatible with angular universal (socket.io in my case). Just removed it.
Universal worked. The issue can be closed.
@abhijeet1403
Can you describe in more detail how you solved this problem?

Fixed: one of the modules was not compatible with angular universal (socket.io in my case). Just removed it.
Universal worked. The issue can be closed.

how did you know ? @abhijeet1403

Any update on this issue?

doing my own private head-bashing on this, it has hit me that when one requests "http://yadyadayada/index.html" that request looks to the server (server.ts) like a request for a static file, so express.static is used rather than res.render...
// Serve static files from /browser
server.get('.', express.static(distFolder, {
maxAge: '1y'
}));
I am willing to bet that if the URL spec'd were "http://yadyadayada/index" (no filetype) the results would be very different (assuming one has not implemented special handling of "index" as a route...
I don't know that this really helps, but may lead to some deeper understanding

Note: for support questions, please use one of these channels. This repository's issues are reserved
for feature requests and bug reports. Also, Preboot has moved here - please make preboot-related issues
there.

  • I'm submitting a ...
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support request here, see note at the top of this template.
  • What modules are related to this Issue?
- [ ] aspnetcore-engine
- [ ] common
- [x] express-engine
- [ ] hapi-engine
- [ ] module-map-ngfactory-loader
  • What is the current behavior?

I followed the instructions on the angular-cli wiki to use universal, all compiled correctly with no errors.

The Universal App fails on http://localhost:4200 the first time it loads but works on http://localhost:4200/index.html

It works fine if I just run a http-server on client folder.

After loading http://localhost:4200/index.html the first time, then http://localhost:4200 is accessible.

The error I receive is 500 with a response of :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Error</pre>
</body>
</html>

Which seems to be a server error.

  • Please tell us about your environment:
  "dependencies": {
    "@amcharts/amcharts3-angular": "^2.0.3",
    "@angular/animations": "5.2.10",
    "@angular/cdk": "5.2.3",
    "@angular/common": "5.2.10",
    "@angular/compiler": "5.2.10",
    "@angular/core": "5.2.10",
    "@angular/forms": "5.2.10",
    "@angular/http": "5.2.10",
    "@angular/material": "5.2.3",
    "@angular/platform-browser": "5.2.10",
    "@angular/platform-browser-dynamic": "5.2.10",
    "@angular/platform-server": "5.2.10",
    "@angular/router": "5.2.10",
    "@angular/service-worker": "5.2.10",
    "@ngrx/effects": "5.1.0",
    "@ngrx/router-store": "5.0.1",
    "@ngrx/store": "5.1.0",
    "@ngrx/store-devtools": "5.1.0",
    "@nguniversal/express-engine": "^5.0.0",
    "@nguniversal/module-map-ngfactory-loader": "^5.0.0",
    "@ngx-share/buttons": "^5.0.0-beta.3",
    "@ngx-share/core": "^5.0.0-beta.3",
    "@nrwl/nx": "0.8.0",
    "@swimlane/ngx-datatable": "^11.1.5",
    "@toverux/ngx-sweetalert2": "^3.0.1",
    "amcharts3": "github:amcharts/amcharts3",
    "angular2-jwt": "^0.2.3",
    "classlist.js": "^1.1.20150312",
    "core-js": "^2.4.1",
    "google-libphonenumber": "^3.0.9",
    "lodash": "^4.17.4",
    "ng2-cookies": "^1.0.12",
    "ng2-pagination": "^2.0.1",
    "ngx-chips": "^1.6.1",
    "ngx-clipboard": "9.1.3",
    "ngx-order-pipe": "^2.0.1",
    "ngx-toastr": "^8.3.2",
    "ngx-uploader": "^4.2.4",
    "papaparse": "^4.3.6",
    "query-string": "^5.1.0",
    "raven-js": "^3.24.2",
    "rxjs": "^5.5.10",
    "socket.io-client": "^2.0.4",
    "sweetalert2": "^7.0.6",
    "tm-intro.js": "^2.9.0-alpha.1",
    "vis": "^4.21.0",
    "web-animations-js": "^2.3.1",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/core": "0.5.7",
    "@angular-devkit/schematics": "0.5.7",
    "@angular/cli": "1.7.4",
    "@angular/compiler-cli": "5.2.10",
    "@angular/language-service": "5.2.10",
    "@nrwl/schematics": "0.8.0",
    "@types/intro.js": "^2.4.3",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "@types/vis": "^4.21.0",
    "codelyzer": "~3.1.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "ngrx-store-freeze": "^0.2.0",
    "npm-run-all": "^4.1.2",
    "prettier": "1.10.2",
    "protractor": "~5.1.2",
    "ts-loader": "^3.5.0",
    "ts-node": "~3.2.0",
    "tslint": "~5.3.2",
    "typescript": "2.6.2",
    "webpack-node-externals": "^1.6.0"
  }
  • Other information (e.g. detailed explanation, stacktraces, related issues, suggestions how to fix, links for us
    to have context, eg. stackoverflow, gitter, etc)

bigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gifbigbluebuttonbn/pix/i/processing16.gif

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mmeylan picture mmeylan  路  4Comments

jeffwhelpley picture jeffwhelpley  路  4Comments

ahmedwerpx picture ahmedwerpx  路  4Comments

moczix picture moczix  路  5Comments

leon picture leon  路  4Comments