Search code examples
angularnpmserver-side-rendering

Angular error when run this command "npm run dev:ssr" to watch the website how server side rendering is done in localhost


When run this command it start listening at port 4200 but it continuously loading the page but never load the page and show this error in cmd.

Unhandled Promise rejection: connect ECONNREFUSED 127.0.0.1:6379 ; Zone: <root> ; Task: Promise.then ; Value: Error: connect ECONNREFUSED 127.0.0.1:6379
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16) {
  errno: -4078,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 6379
} Error: connect ECONNREFUSED 127.0.0.1:6379
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16)

File :- server.ts

Actually I am facing the problem that in ngAfterViewInit function I have a created the function of scroll down but in that function for particular element of HTML the id didn't fetch its because the component is still not loading and I think that there is an error in ssr but for running command to watch in ssr mode in localhost it will show the above error in cmd. So here I have given server.ts file as some one requested in the comment.

import 'dotenv/config';
import { join } from 'path';
const domino = require('domino');
import * as request from 'request';
import * as express from 'express';
import * as compress from 'compression';
import * as cookieparser from 'cookie-parser';
import 'zone.js/node';
import { ngExpressEngine } from '@nguniversal/express-engine';
import { REQUEST, RESPONSE } from '@nguniversal/express-engine/tokens';
import { APP_BASE_HREF } from '@angular/common';
import { existsSync, readFileSync } from 'fs';
import 'localstorage-polyfill';
import { environment } from './src/environments/environment';
import { AppServerModule } from './src/main.server';
import { httpAuth } from './src/server/http-auth';
import { cacheResponse, cachedResponse } from './src/server/caching';

const distFolder = join(process.cwd(), 'dist/browser');
const indexPath = join(distFolder, 'index.html');
const indexHtml = existsSync(indexPath) ? 'index.html' : 'index';
const win = domino.createWindow(readFileSync(indexPath).toString());
win.Object = Object;
win.Math = Math;

global.localStorage = localStorage;
global.window = win;
global.document = win.document;
global.branch = null;
global.object = win.object;
(global as any).navigator = win.navigator;

export async function app(): Promise<express.Express> {
  const server = express();

  server.use(compress(), cookieparser());

  if (environment.staging) {
    server.use(httpAuth);
  }

  server.engine('html', ngExpressEngine({ bootstrap: AppServerModule }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

  server.get('/sitemap.xml', (req, res) => {
    request(
      `${environment.apiUrl}/sitemap.xml`,
      { json: true },
      (err: Error, _res, body) => {
        if (err) return console.warn(err);

        res.setHeader('Content-Type', 'application/xml');
        res.end(body);
      }
    );
  });

  server.get('*.*', express.static(distFolder, { maxAge: '1y' }));

  // All regular routes use the Universal engine
  server.get('*', cachedResponse, (req, res) => {
    res.render(
      indexHtml,
      {
        req,
        providers: [
          { provide: APP_BASE_HREF, useValue: req.baseUrl },
          { provide: REQUEST, useValue: req },
          { provide: RESPONSE, useValue: res },
        ],
      },
      cacheResponse(req, res)
    );
  });

  return server;
}

function run(): void {
  const port = process.env.PORT || 4000;

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

declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = (mainModule && mainModule.filename) || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  run();
}

export * from './src/main.server';

Solution

  • Install the redis server and then run the file redis-server.exe. Then run the command of SSR "npm run dev:ssr".