What is the process for exporting a class and declaring middleware in TypeScript?

After creating the user class where only the get method is defined, I encountered an issue when using it in middleware. There were no errors during the call to the class, but upon running the code, a "server not found" message appeared. Surprisingly, deleting the line app.use(userRoute) resolved the server error.

users.ts

import { NextFunction, Request, Response } from 'express';
import { Controller, Get, Req, Res } from 'routing-controllers'

@Controller()
class User {
    @Get('/signup')

    signUP(@Req() req: Request, @Res() res: Response, next: NextFunction) {
        return res.render('signup')

    };
}

export { User as userRoute }

app.ts

const express = require('express')
const path = require('path')
const app = express()
import { userRoute } from "./routes/user";

const bodyPaser = require('body-parser')


app.use(bodyPaser.urlencoded({ extended: true }))
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')


app.use(userRoute)

app.use('/', (req, res) => {

    res.write('<html lang="eng">');
    res.write('<head><title>Page</title><style>body{background-color: wheat; color: red; font-      size: 25px; padding-left: 250px;}.d{}</style></head>')
    res.write('<body><h1>It is working</h1></body>')
    res.write('</html>')
    return res.end()
});

app.listen('3000')
console.log('working')

Answer №1

make sure to instantiate your class before exporting it. You can do something like this:

class User {
...
}

const userRoute =  new User()
export {userRoute}

Based on the documentation of routing-controllers

as per the instructions in the github page of the library, when using express, it should be implemented as follows:


@Controller()
export class UserController {

    @Get("/users")
    getAll(@Req() request: Request, @Res() response: Response) {
        return response.send("Hello response!");
    }

}


import "reflect-metadata";
import { useExpressServer } from "routing-controllers";

let express = require("express"); // or you can import it if you have installed typings
let app = express(); // your created express server
// app.use() // you can configure it the way you want
useExpressServer(app, { // register created express server in routing-controllers
    controllers: [UserController] // and configure it the way you need (controllers, validation, etc.)
});
app.listen(3000); // run your express server

refer to their documentation for more details

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

Is there a way to bring in a variable from the front end script?

Is it possible to transfer an array of data from one HTML file to another? If so, how can this be done? Consider the following scenario: First HTML file <script> let tmp = <%- result %>; let a = '' for (const i in tmp){ ...

Incorporate JSON information into a sleek Bootstrap modal interface

I am looking to load a JSON file to generate a list within a Bootstrap Modal. The setup I have allows for the modal to appear when clicking on a person's image. <li class="project span3" data-type="pfa"> <a data-toggle="modal" data-targe ...

The Angular Function has stopped working out of the blue following the implementation of Jquery Ajax

As a newcomer to php programming, I am facing an issue with my Angular Function not functioning properly when incorporating a jQuery ajax method post to update values in the database. Below is my angular code within HTML: <tfoot ng-app="kembalianApp" ...

The Swagger documentation does not display the API response after attempting to execute the request

After creating an API document for one of my post requests, I encountered an issue. The request body was added without any errors, but when I tried to execute it, the operation would just load and then close without displaying any success or error message ...

What purpose does the array.pop()!(object) syntax serve within Codemirror?

Within the Codemirror 6 documentation and at line 41 of the code, there is a snippet that reads: while (pending.length) pending.pop()!(data.updates) I'm curious about the meaning of this syntax. It appears to be TypeScript specific. How would this lo ...

What is the best way to extract URLs with varying numbers of slashes in angular.js?

My goal is to create an Angular website focused on managing files, allowing users to navigate through a file system tree similar to how it's done on Github (example: github.com/angular/angular.js/tree/master/path/to/my/file.js. I want to extract the ...

Execute various Office Scripts functions within a single script based on the button that is selected

Imagine you have an Excel spreadsheet with two buttons named populate-current and populate-all. Both buttons execute the same Office Script function that looks something like this: function populateByRowIndex(workbook: ExcelScript.Workbook, rowIndex: numbe ...

What is the best way to ensure a consistent time interval between invoking two functions in JavaScript?

Is there a way to create a code that will call one function, let's say toStart(), and then immediately call another function, toStop(), exactly two seconds after the first function is initiated? I want this process to continue until a specific button, ...

Understanding the meaning of `.then()` in Excel JavaScript involves recognizing its function

Excel.run(function (context) { var sheet = context.workbook.worksheets.getItem("Sample"); var range = sheet.getRange("B2:C5"); range.load("address"); return context.sync() .then(function () { ...

Assign the array value to all inputs that share the same class tag

Does anyone know how to iterate through all tags with the same className and retrieve their values? var quantities = []; $(".add_more_items").each(function(){ quantities.push($(this).val()); }); Here is an example of the result: ['1&apo ...

A guide on incorporating Typescript into Material UI v5 themes

A similar question has been asked previously, however... I am looking to enhance my color options by adding variants such as success, warning, and more choices within the background category (palette.background). Specifically interested in a lite option t ...

Unable to retrieve options from a particular select box

Utilizing cheerio and nodejs to scrape all the countries listed on a website, I have implemented the following code: const rp = require('request-promise'); const cheerio = require('cheerio'); const options = { uri: 'https://u ...

How to achieve the functionality of ocibindbyname in JavaScript

I am currently utilizing an HTA page that is coded in JavaScript to monitor various Oracle tables. My goal is to optimize the Oracle query caching by using bind variables, similar to how I implemented it in a PHP environment with this code: $sql = "selec ...

The scrolltop function is dysfunctional on CentOS operating systems

I'm currently working on implementing smooth scrolling functionality when a button is clicked. The feature works perfectly fine with a local Apache server and IE10+, but when the project is deployed on "CentOS", it doesn't work on the same browse ...

Is it necessary to have nodejs, or can I just depend on Nginx alone?

I am currently in the midst of a discussion with my colleagues regarding whether or not to incorporate node.js into our application. We have decided to utilize angular.js for the front-end and communicate with the app server through a REST api. The app ...

Working on asynchronous processing of Highland stream fragments

My current setup involves utilizing highland.js to process a file using a stream and extract content between specific delimiters. Additionally, I am incorporating async.js to perform a sequence of http requests. I am seeking a way to pass the output x fro ...

In React (Next.js), the act of replacing a file is performed instead of adding a file

I kindly request a review of my code prior to making any changes. const test = () => { const [files, setFiles] = useState ([]); //I believe I need to modify the following statement. const handleFile = (e) => { const newFiles = [] for (let i= ...

Multiple jQuery load() requests are being triggered by calling it from within the ajaxComplete() callback

I've been stuck on this issue for quite some time now. To troubleshoot, I suggest using Firebug to inspect the AJAX requests. It seems that they are multiplying with each click of the next and previous buttons, causing the page to load slowly: You ca ...

Remove objects from an array if they share identical key values

I'm having trouble getting this to work. I have an array of objects that looks like this: let myCities = [ { value: 'Barcelona', code: 02342837492482347 }, { value: 'Rome', code: 28282716171819 }, { v ...

Step-by-step guide to minify Typescript files with Webpack

I am facing an issue in my webpack configuration while trying to minify the output bundle when working with TypeScript. Currently, only one file has been migrated to TypeScript in my project and it works fine with babel-node and the dev bundle without Ugli ...