TypeScript Express Restful API don't register routes

Issue

I have created simple REST API for my Application.
At the beginning API was written in JavaScript and everything works fine.
I decided to switch to TypeScript. With couple changes related to types, adding ts config file, Express-TypeScript server was running. However when I tested the API with http client, request hang as if no route was registered by Express. I tried to diagnose the problem and I have defined routes directly in index.ts file and works properly. Seems like there is some problem with createServer.ts helper function. If you have any idea what might be wrong I’ll be glad to hear explanation, thank you in advance!

createServer.ts

import express, { Application } from "express";
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import validateToken from "../middleware/validateToken";
import cors from "cors";

// routes
import user from "../routes/user";
import note from "../routes/note";
import speechRecognition from "../routes/speechRecognition";

cors({ origin: "http://localhost:5000", credentials: true });

function createServer(): Application {
  const app = express();

  app.use(cors);
  app.use(express.json());
  app.use(
    express.urlencoded({
      extended: true,
    })
  );
  app.use(cookieParser());
  app.use(bodyParser.urlencoded({ extended: false }));

  app.use(
    validateToken.unless({
      path: [
        { url: "/user", method: "POST" },
        "/user/authenticate",
        "/user/refresh-token",
      ],
    })
  );

  app.use("/user", user);
  app.use("/note", note);
  app.use("/api", speechRecognition);

  return app;
}

export default createServer;

index.ts

import { path } from "app-root-path";
import { Port } from "./types/Port";
import { Application } from "express";

// env
import { config } from "dotenv";
config({ path: `${path}/../.env` });

// express
import createServer from "../server/utils/createServer";

// db connection
import { dbConnection } from "../server/db/connection";

dbConnection(process.env.DB_URI as string);

const app: Application = createServer();

const port: Port = process.env.PORT || 3000;

app.listen(port, () => console.log(`Server is running on port: ${port}`));

tsconfig.json

{
  "compilerOptions": {
    "esModuleInterop": true,
    "moduleResolution": "node"
  }
}

package.json script

"server": "ts-node-dev index.ts",

Solution

You’re not using the cors middleware correctly:

function createServer(): Application {
  const app = express();

  app.use(cors({ origin: "http://localhost:5000", credentials: true }));
  …
}

Answered By – robertklep

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published