1

I'm trying to figure out why the routing doesn't work if I use expressjs, I have this code:

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

app.get('/foo', function (req, res) {
    res.send('Hello World.')
});

the code above works well, but if I replace the route with this:

router.get('/foo', function(req, res, next) {
    res.send('This is api.')
});

I get:

Cannot GET /foo when using express.Router()

sfarzoso
  • 1,356
  • 2
  • 24
  • 65

3 Answers3

2

You are missing the following: app.use(router); Towards the bottom of your code. You'll also need app.listen(3000); Or whatever port you want to run your application on.

Full example:

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

router.get('/foo', function (req, res, next) {
    res.send('This is api.')
});

app.use(router);
app.listen(3000);
Bryan
  • 955
  • 2
  • 7
  • 18
  • just a question: is better use router or app with post, get ...? – sfarzoso Mar 04 '19 at 19:56
  • @sfarzoso Depends on how complicated your app is. Maybe check out https://stackoverflow.com/questions/28305120/differences-between-express-router-and-app-get to get some ideas. – Bryan Mar 04 '19 at 20:01
1

You need to configure each router properly in order to use it in Express.

In your root server file (index.js/app.js) you need to register the router with the app. For example:

const express = require("express");
const app = express();

const fooRouter = require("./routes/foo");
app.use("/foo", fooRouter);

Then in routes/foo.js you can use your code as before ("but note that route paths will be relative to "/foo" a this point), but you also need to export the router. For example:

const express = require("express");
const router = express.Router();

router.get("/bar", (req, res) => {
    // ...
});

module.exports = router;

Where the final route will be "/foo/bar". For just "/foo", you can define a handler for "/" within foo.js.

Henry Woody
  • 14,024
  • 7
  • 39
  • 56
0

You might have mistakenly used app.get(router) instead of app.use(router).

TrungDC19
  • 1
  • 2
  • Hi, this is an old question, and has an already accepted answer. Take the [tour](https://stackoverflow.com/tour) and welcome here in SO – pierpy Apr 12 '23 at 17:31