`Express routes in TypeScript`

Recently, I have been following a tutorial on how to build a Node.js app with TypeScript. As part of the tutorial, I attempted to organize my routes by creating a separate route folder and a test.ts file containing the following code:


import {Router} from "express";

let router = Router();
router.get('/', get);

export async function get(req, res, next) {
    try {
        res.send("Testing...");
    } catch (err) {
        console.log('err', err);
        next(err);
    }
}

export {router};

I then tried to integrate this route into my server.ts file like so:


import * as express from "express";
import * as TestRoute from './routes/test';

class App {
    public express : express.Application;

    constructor() {
        this.express = express();
        this.mountRoutes();
    }

    private mountRoutes() : void {
        const routes: express.Router = express.Router();
        routes.use('/test', TestRoute);
        this.express.use('/', routes);
    }
}

export default new App().express;

However, when using routes.use('/test', TestRoute);, TypeScript raised an error indicating that the types were not assignable. The error message specifically mentioned the missing 'includes' property.

I am seeking help in understanding and resolving this error. Additionally, I would appreciate any guidance on structuring routes and incorporating them into TypeScript applications. My current TypeScript version is 2.7.

Answer №1

Your issue lies in the import statement within the server.ts file, specifically in how you are utilizing the module.

Upon examining the TestRoute object, it appears to function solely as a module that encapsulates all your exported content. Therefore, you must find a way to access the router object within it. There are two possible solutions:

  1. Modify your import statement in server.ts to read as follows:
    import { router as TestRoute } from './routes/test';
  2. Alternatively, adjust how you access the module in your routes.use line by using this syntax instead:
    routes.use('/test', TestRoute.router);

You can choose either approach, as both will resolve the issue, but remember to implement only one of them!

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

Electron with integrated REST API

I currently have an API created with express.js and I am interested in developing a similar application using electron.js. Is there a method to utilize the express API within electron without having to redo all the work? ...

Manage numerous receiving bank accounts, allowing customers to transfer money to each specific account

Managing multiple receiving bank accounts and enabling customers to transfer money to specific accounts is a key requirement in my application. Can Plaid help me achieve this functionality? Could you provide guidance on how to implement this feature using ...

The data structure '{ recipe: null; }' cannot be matched with type 'IntrinsicAttributes & Recipe'

Currently, I am working on an app that integrates ChatGPT to fetch recipes based on user-input ingredients. After receiving the JSON response from CGPT, I aim to display a Recipe "Card" component. However, I encounter an error titled above when attempting ...

Angular version 5 and above introduces a new feature called "openFromComponent" within the Snackbar component, facilitating seamless communication

Angular (v5.2.10) Snackbar --| Introduction |-- I am facing a scenario where an Angular component named "Parent" is initializing an Angular Material Snackbar known as snackBar. The snackbar is being passed in the component called SnackbarMessage, which ...

Guidelines for dynamically displaying <router-link> or <a> in Vue based on whether the link is internal or external

<template> <component :is="type === 'internal' ? 'router-link' : 'a'" :to="type === 'internal' ? link : null" :href="type !== 'internal' ? link : null" > <slot /> < ...

Display information from Node.js on an HTML page

I am working on a nodejs project where I need to login on one page and display the result on another page using expressjs. Below is my code for login.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <body> <form method="PO ...

What is the process for configuring a TimePicker object in antd to send a Date with UTC+3 applied?

I have Form.Item and a TimePicker defined inside it. I am using this form to send a POST request, but when I try to post 16:35, it gets sent as 13:35. The UTC offset is not being considered. However, the CreationTime works fine because it utilizes the Da ...

Having trouble executing the project using Gulp

I'm a beginner in front-end development and I am working on an existing project that I'm having trouble running. According to the documentation, I should run the project by executing: $ gulp && gulp serve But I keep getting this error: ...

Setting up node.js alongside the express module

I'm currently running the latest stable version of Debian. Although I can successfully use apt-get install nodejs, I encountered an issue when trying to install npm using apt. Instead, I had to manually compile it by using wget http://nodejs.org/dist/ ...

An easy way to insert a horizontal line between your text

Currently, I have two text responses from my backend and I'm considering how to format them as shown in the design below. Is it possible to automatically add a horizontal line to separate the texts if there are two or more broadcasts instead of displa ...

Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...

Using TypeScript to create a generic type that wraps around HTMLElements

I attempted to execute this action, however the assignment to this.element is not working and I am unsure why. class Elem<T> { public element : T; constructor(typeElement:string){ this.element = document.createElement(typeElement); ...

Node.js and Express: Failure to establish headers once they have already been sent to the client

Exploring the code snippet below, I am attempting to authenticate a user using their credentials from a Mongo DB: { validate: async function (email, password, res) { console.log('Inside validate method'); try { var dbUserObj = a ...

Having difficulty retrieving data when running a React JS app on the IP address 192.168.XX.XXX

I'm attempting to retrieve backend data in a React app using the Fetch API. It's functioning correctly when I run the React app on localhost, but if I change the address from localhost to an IP, it stops working and displays Unhandled Rejection ( ...

Building a node.js application with a mongoDB database from scratch

I am encountering an issue while attempting to print data collection using nodejs and mongo. The error that arises remains unresolved, what steps should be taken to correct this problem? For instance, consider the following schema: const bookSchema = new ...

Creating a Restful API without relying on frontend javascript can be achieved by implementing server-side

I've been on the hunt for a guide to create a RESTful API without relying on frontend JavaScript, but I haven't had any luck so far. As someone new to Javascript and web development, I've been working on tutorials and little projects to fami ...

Do you have an index.d.ts file available for canonical-json?

I am currently working on creating an index.d.ts file specifically for canonical-json. Below is my attempted code: declare module 'canonical-json' { export function stringify(s: any): string; } I have also experimented with the following sn ...

Guide on saving the token in local storage or cookies to grant access to specific web pages for users

Currently, I am in the process of developing an authentication system using Node.js, MySQL, and Express. Initially, I focused on saving and verifying user credentials in the database. Recently, I incorporated JWT (JSON Web Token) into the system. My next s ...

Show 404 error for Express.js routes only in production environment

I've been working on creating a video conferencing application based on this guide. While the tutorial was helpful during development, I encountered issues when trying to push the application to production. Unfortunately, my familiarity with these to ...

Is it possible to insert clickable links within the content of a Twilio text message?

Currently, I am utilizing Twilio and Express to send programmable SMSs to the users of my web application. I'm curious if it's possible to include hyperlinks within the body of these text messages. Is there a method to achieve this? I have attem ...