-1

I would like to check the route when receiving a request in nodejs (10.16) and express (4.16) project. The server listens to port 3000 on localhost. Here is a users route:

const users = require('../routes/users');

module.exports = function(app, io) {
    app.use('/api/users', users);
}

In route users.js, there is:

router.post('/new', async (req, res) => {...}

When a route is called (ex, ${GLOBAL.BASE_URL}/api/users/new), how do I know which route is being called from the param req?

user938363
  • 9,990
  • 38
  • 137
  • 303

2 Answers2

1

OK, what I understand, you are having troubles accessing your user routes (declared in your users.js file) from your application root file.

Because you are modularize your routes, you need to make sure you export your routes module to gain access from another file:

app.js:

const UserRouter = require('../routes/users');

module.exports = function(app, io) {
    app.use('/api/users', UserRouter);
}

users.js:

const UserRouter = express.Router()

UserRouter.post('/new', async (req, res) => {...};


module.exports = UserRouter;

  • NO, those are done and routes works fine. I just need to know which route is being called. – user938363 Aug 09 '19 at 21:46
  • 1
    Ok now I get it, if you want to have the complete URL of the called request you can extract it directly from your req as you want with this: `let completeUrl = req.protocol + "://" + req.get('host') + req.originalUrl; ` Or if you preffer a more clean implementation you can use the `url` module: ` import url from 'url' extractUrl = (req) => return url.format({protocol: req.protocol, host: req.get('host'), pathname: req.originalUrl}); ` – Fernando__1 Aug 09 '19 at 21:53
  • Found this post https://stackoverflow.com/questions/12525928/how-to-get-request-path-with-express-req-object – user938363 Aug 09 '19 at 21:58
0

If you need the path of request, Try this:

var path = url.parse(req.url).pathname;
console.log('path:', path);
Majdi Mohammad
  • 139
  • 1
  • 4