Search code examples
typescriptexpress-router

Can't use exported module for express router as middleware


I'm trying to separate out the routes from the server file, however I can't seem to get my route controller to export whether I try to use require('') or import as syntax for the module export

My server.ts file

import express from 'express';
import * as dotenv from 'dotenv';
import cors from 'cors';
import cookieParser from 'cookie-parser';

dotenv.config();

//Routing setup
const userRoutes = require('./api/users/controller');
const app = express();
const port = process.env.PORT;

const CORSOPTIONS = {
    origin: "*",
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    preflightContinue: false,
    optionsSuccessStatus: 204
}

app.use(cors(CORSOPTIONS));
app.use(cookieParser());
app.use(express.json());

app.use('/login', userRoutes);

// app.post('/login', (req: Request, res: Response) => {
//     console.log('USER ATTEMPTED LOGIN');
//     res.send('LOGGED IN');
// });

app.listen(port, () => {
    console.log(`[server]: Server is running at http://localhost:${port}`)
});

my api/user/controller.ts file

import express, { Request, Response, Router } from 'express';

const userRoutes = Router();

userRoutes.post('/login', (req: Request, res: Response) => {
    console.log('USER ATTEMPTED LOGIN');
    res.send('LOGGED IN');
});

module.exports = userRoutes;

//export default userRoutes;

Am I missing something really obvious? There is nothing wrong with post method because if I just put the route directly in server it gets a response but exporting it just returns "Cannot POST /login"


Solution

  • The router handles a path /login (userRoutes.post('/login')

    You’ve mounted the router at /login (app.use('/login', userRoutes);)

    That makes the full path /login/login but you are requesting just /login