1

I have a express app.js with typical

app.get('/path1', (req, res => {}) 
app.get('/path2', (req, res => {}) 
app.get('/path3', (req, res => {}) 

now I want to catch all routes, starting with api such as below and redirect them to their corresponding handler in express but not sure how to achieve that

/api/path1 
/api/path2 
/api/path3 

I' assuming i can have a catch all api as below

app.all('/api/*', function (request, response, next) { //in a server.js file 
       //how can i call the corresponding paths here?? 
       // looking for something to do forward to current-route.replace('api','') 
       // or something like that 
})
nightograph
  • 2,179
  • 5
  • 31
  • 49

2 Answers2

1

Maybe a router-level middleware could solve your problem:

const router = express.Router();

router.get('/path1', (req, res => {});
router.get('/path2', (req, res => {});
router.get('/path3', (req, res => {});

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

Update:

Use redirect (not that much of a difference to your current solution; not tested):

app.all('/api/*', (request, response) => res.redirect(request.url.replace('/api', '')));
pzaenger
  • 11,381
  • 3
  • 45
  • 46
  • sorry maybe i should had been more clear, trying to run both express and react from the same port and wanted to send non api calls to res.sendFile(path.join(__dirname, 'build', 'index.html')) – nightograph May 14 '20 at 18:29
  • 1
    actually yes, I can use this in combination with app router! thank you – nightograph May 14 '20 at 18:40
0

this worked for me, please let me know if there is a better way

app.all('/api/*', function (request, response, next) {
    request.url = request.url.replace('/api','');
    next();  
})
nightograph
  • 2,179
  • 5
  • 31
  • 49