The idiom 'listen' is not recognized within the context of type 'Express'. Try using a different property or method to achieve the desired functionality

Encountering an error in VS Code while working on an Angular 13 app that utilizes Angular Universal for Server Side Rendering. The specific error message is:

Property 'listen' does not exist on type 'Express'.ts(2339)

This error occurs at the line: server.listen(port, () => { in the file server.ts as shown below:

const MockBrowser = require('mock-browser').mocks.MockBrowser;
const mock = new MockBrowser();
global['window'] = mock.getWindow();
global['document'] = mock.getDocument();
global['navigator'] = mock.getNavigator();
import 'globalthis/auto';
import 'zone.js/dist/zone-node';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';

import { AppServerModule } from './src/src';
import { APP_BASE_HREF } from '@angular/common';
import { existsSync } from 'fs';

// Exporting the Express app for potential serverless Functions usage.
export function app(): express.Express {
  const server = express();
  const distFolder = join(process.cwd(), 'dist/bbc/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';

  // Implementing our Universal express-engine
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
  }));

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

  // Example API endpoints with Express
  // server.get('/api/**', (req, res) => { });
  // Serving static files from /browser
  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  // Using the Universal engine for all regular routes
  server.get('*', (req, res) => {
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

  return server;
}

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

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

The codebase employs Typescript 4.4. Open to suggestions on modifications required in the server.ts file.

Answer №1

After updating from Angular 11 to 14, I encountered a similar error in my project. It took me hours of cleaning up unnecessary code and removing deprecated packages from package.json before I was finally able to get the app working again with Angular 14. As I debugged further, I noticed that some essential packages were missing from the imports at the top of your file - once I added them back, the error disappeared. Hopefully, this helps you resolve the issue as well!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering Error with NodeJS Typescript: Issue with loading ES Module when running sls offline command

I have come up with a unique solution using NodeJS, Typescript, and Serverless framework to build AWS Lambdas. To debug it locally in VS Code, I use the serverless-offline library/plugin. You can find my project on GitHub here However, when I run the comm ...

Troubleshooting: Vue and TypeScript Components Not Communicating

Vue is still fairly new to me and I'm struggling with this issue. Despite following code examples, my implementation doesn't seem to be working correctly. The component I defined looks like this: <template> <div class="row"> ...

Exploring Angular 7: Leveraging class inheritance and the powerful httpClient

It has come to my attention that my services are quite repetitive. In an attempt to enhance them, I decided to delve into super classes and inheritance in Angular. However, I have been struggling with the constructor and super calls. Despite TypeScript com ...

Avoiding resources in Passport.js

Currently, I am developing an API endpoint using expressjs and securing it with passportjs (by utilizing the jwt strategy). The issue I am facing is that if I place the /login endpoint outside of the /api path, everything functions correctly. However, I w ...

"Utilizing Node.js with Socket.io and Express version 3 for dynamic web

I am new to Node.js and Express, and I am facing an issue with accessing the socket.io object in other modules. I tried creating a global variable to hold a socket object, but once the connection is closed by the user, the socket becomes unavailable. Altho ...

Tips for enlarging the font size of a number as the number increases

Utilizing the react-countup library to animate counting up to a specific value. When a user clicks a button, the generated value is 9.57, and through react-counter, it visually increments from 1.00 to 9.57 over time. Here's the code snippet: const { ...

Utilizing MakeStyles from Material UI to add styling to a nested element

I was pondering the possibility of applying a style specifically to a child element using MakesStyles. For instance, in a typical HTML/CSS project: <div className="parent"> <h1>Title!</h1> </div> .parent h1 { color: # ...

Having difficulty showing an image in the navigation provided via useContext()

The image is successfully displaying in the Profile.js screen and other areas. However, when attempting to pass the image via useContext() to display in Navigation.js, it shows as src(unknown). What could be causing this issue? https://i.stack.imgur.com/w ...

`Controlling and Organizing node.js Middleware`

When developing middleware that works in conjunction, what is the best practice for organizing and managing their functionality? Currently in my server.js file, I have them simply listed one after another with app.use calls. I've realized that if th ...

Tips for successfully passing a prop to a custom root component in material-ui@next with TypeScript

Is there a way to properly render a ListItem component with react-router Link as the root component? Here's the code snippet in question: <ListItem to="/profile" component={Link} > Profile ...

Creating a new object in an empty array within my profile model (mongodb/mongoose) is simple. Just follow these steps to successfully add a

Presenting my Profile model: const ProfileSchema = new mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "User", }, company: String, website: String, location: String, status: { type: String, require ...

Angular: issue with form validation - password matching is not functioning as expected

I have successfully implemented the registration form with basic validations The code I used can be found in: registration.html <form #registrationForm="ngForm" (ngSubmit)="onFormSubmit()"> ... <div class="form- ...

Exploring Angular 4: Iterating Over Observables to Fetch Data into a Fresh Array

Context Currently, I am in the process of developing a find feature for a chat application. In this setup, each set of messages is identified by an index. The goal of the `find()` function is to retrieve each message collection reference from the `message ...

Angular.js encountered an error with the Injector.modulerr function

I'm facing an issue with my node-jade-angular application: layout.jade doctype html html(ng-app='listApp') head title= title script(src='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.10/angular.min.js') ...

What is the best way to display the values from an array in a child component and pass them to the

How can I retrieve values from an array in the child component and display that data in the parent component? Initially, I was only displaying data from the array when the 'save' button was clicked. Now, I need to display the array by default. ...

get a collection of chosen files in angular 7 and save them to

Greetings, I am currently working on a project and encountering an issue. I need to download multiple selected files from a list, but despite my efforts in searching for a solution, I have been unable to find one. While I can successfully download single f ...

Making strides in file uploads with formidable

For my backend using node.js-express with the formidable package, I attempted to integrate a progress bar utilizing formidable and websockets: const create = (req, res, io) => { logger.debug(`EXEC create material`) const form = new formidable.Incom ...

The maxBodySize feature is ineffective in restify

I am currently running a node app on version v0.10.33 with the Restify module ^2.8.3 installed. var app = restify.createServer(); app.use(restify.queryParser()); app.use(restify.bodyParser({ maxBodySize: 1, //Issue: The limit is not being enforced at th ...

Modifying ngModel will result in the corresponding ngModel in another Angular2 browser being updated

I'm a novice when it comes to Angular 2 and I'm currently working on a project using npm to run the application. At the moment, I have it hosted on localhost with port 3000. The issue I'm facing in my project is that when I open the same ...

Is it possible that React.createElement does not accept objects as valid react children?

I am working on a simple text component: import * as React from 'react' interface IProps { level: 't1' | 't2' | 't3', size: 's' | 'm' | 'l' | 'xl' | 'xxl', sub ...