Wai Yan Hein
Wai Yan Hein

Reputation: 14791

Express JS (Node): adding the prefix to routes is not working

I am building a web application using the Node JS Express JS framework. Now, I am trying to add a prefix to all the routes of my application. But it is not working.

This is how I did it.

let express = require('express');
let app = express();
const apiRouter = express.Router()

apiRouter.use('/api', () => {
  app.get('/auth', (req, res) => {
    res.send("Auth route")
  })

  return app;
})

When I go to the '/api/auth' in the browser, I am not getting the expected response. I am getting the following error.

Cannot GET /api/auth

What is wrong with my code and how can I fix it?

Upvotes: 2

Views: 1476

Answers (3)

hoangdv
hoangdv

Reputation: 16137

Try to make it simple at first:

let express = require('express');
let app = express();
const apiRouter = express.Router();

apiRouter.get('/auth', (req, res) => {
  // handle GET /auth method
  res.send("Auth route");
});

// register handle for any request with Endpoint like /api/* (api/"anything include auth")
app.use('/api', apiRouter);

app.listen(3000, () => {
  console.log(`Server started on port`);
});;

Upvotes: 0

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

It is because app.use is to add middleware(to specific request you add for particular path) to your request and to respond by matching the exact path to it. You can read more details here it is a very detailed thread.

let express = require('express');
let app = express();
const apiRouter = express.Router();

//create route file which will handle the exact match for it;
const apiRouteHandler = require('path');

app.use('/api', apiRouteHandler)

Sample apiRouteHandler

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

router.get('/auth', function(req, res){
   res.send('GET route on things.');
});

//export this router to use in our index.js
module.exports = router;

Cannot GET /api/auth

This errors comes in because app unable to match this route anywhere as in the middleware app.get won't we invoked like this. You need to create a route handler for that and then it routing mechanism of express will pass on to the correct handler in the route file.

Upvotes: 1

Tony Yip
Tony Yip

Reputation: 750

You need to use express.Router

https://expressjs.com/en/guide/routing.html#express-router


const router = express.Router();
router.get('/auth', (req, res) => {
  res.send("Auth route");
});

apiRouter.use('/api', router);

Upvotes: 1

Related Questions