user2024080
user2024080

Reputation: 5091

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.

Upvotes: 0

Views: 206

Answers (3)

Mesar ali
Mesar ali

Reputation: 1898

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");
});

Upvotes: 1

Yossi Bavaro
Yossi Bavaro

Reputation: 11

Use app.use

Example

app.use('/c', c);

Upvotes: 0

richardsefton
richardsefton

Reputation: 370

You need the app to consume the router.

Try adding app.use('/route', router);

Upvotes: 0

Related Questions