Search code examples
node.jsexpressexpress-router

express.js - basic application router not working


I just creating a basic app, but it seems not working for me. any one help me to find the mistake?

here is my code :

import express from "express";

const app = express();
const router = express.Router();


app.use((req, res, next) => {
    console.log("first middleware");
    next();
});

router.get("/a", (req, res, next) => {
    res.send("Hello this is route a");
});

router.post("/c", (req, res, next) => {
    res.send("Hello this is route c");
});

app.listen({ port: 8000 }, () => {
    console.log("Express Node server has loaded");
});

Node version : v14.17.5 Express version : ^4.17.1

thanks in advance.


Solution

  • Use the router

    import express from "express";
    
    const app = express();
    const router = express.Router();
    
    
    router.get("/a", (req, res, next) => {
    res.send("Hello this is route a");
    });
    
    router.post("/c", (req, res, next) => {
       res.send("Hello this is route c");
    });
    
    app.use(router, (req, res, next) => {
      console.log("first middleware");
      next();
    });
    
    app.listen({ port: 8000 }, () => {
      console.log("Express Node server has loaded");
    });