0
votes

I have a simple app which is written by nodejs, express, and typescript. But I get an error while calling the root route. The server is started successfully but I cannot find the problem. My codes:

server.ts

import app from "./app";
const PORT = 3001;    
app.listen(PORT, () => {
    console.log('Express server listening on port ' + PORT);
})

appRoutes.ts

import {Request, Response} from "express";
export class Routes {       
    public routes(app): void {          
        app.route('/')
        .get((req: Request, res: Response) => {            
            res.status(200).send({
                message: 'GET request successfulll!!!!'
            })
        })               
    }
}

app.ts

import * as express from "express";
import * as bodyParser from "body-parser";
import { Routes } from "./routes/appRoutes";

class App {

    public app: express.Application;
    public routePrv: Routes = new Routes();

    constructor() {
        this.app = express();
        this.config(); 
        this.routePrv.routes(this.app);            
    }

    private config(): void{
        // support application/json type post data
        this.app.use(bodyParser.json());
        //support application/x-www-form-urlencoded post data
        this.app.use(bodyParser.urlencoded({ extended: false }));
    }

}

export default new App().app;

And I use this command to start the server:

npm run dev

Which shows:

[email protected] dev P:\boolood\nodeversion

ts-node ./lib/server.ts

Express server listening on port 3001

Can anyone help me with this problem?

1
In a command line window there is some message or error or warning, Can you paste those details here? or Check the browser log.Utkarsh Dubey
There's no error! I updated my questionBoolood
This appRoutes.ts is the file which contains a get method, right?Utkarsh Dubey

1 Answers

0
votes

This is not the answer, but It will help you to get the error.

import { Request, Response } from "express";
export class Routes {
    public routes(app): void {
        app.route('/')
            .get((req: Request, res: Response) => {
                //res.status(200).send({
                //    message: 'GET request successfulll!!!!'
                //})

                // If request fails, throw an Error that will be caught
                if (res.status < 200 || res.status >= 300) {
                    throw new Error('This request has failed ' + res.status);
                }
                // If everything went fine, return the response
                else {
                    return res.json();
                }
            })
    }
}