2

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great to hear that! 😀
1

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

1 Comment

Hi are you saying that I need two instances of express router? I am already using it, apiRouter variable.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.