I'm developing an app using VENoM stack, and in the API I have some middleware like this:
const express = require('express');
const router = express.Router();
require('./routes/orderRoutes')(router);
require('./routes/userRoutes')(router);
require('./routes/ftpRoutes')(router);
module.exports = router;
And each router has a different "path", I mean, to call the API the base URL is https://localhost:8081/api/... And each router starts with a different route like /order/... /ftp/... or /user/...
The problem is, that I want to call a GET route from ftpRoutes
to orderRoutes
like this
router.get('/ftp/importFiles', async function(request, response, next) {
client.ftp.verbose = true
try {
await client.access(ftpTest)
let files = await client.list('/');
files = files.map((file) => path.join(downloadsPath, file.name));
console.log(files);
if (!fs.existsSync(downloadsPath)) {
fs.mkdirSync(downloadsPath, { recursive: true });
}
await client.downloadToDir(downloadsPath, '/');
console.log(files)
request.session.files = files;
} catch (err) {
console.log(err)
}
client.close()
})
And from this route, that is http://localhost:8081/api/ftp/importFiles I want to call to http://localhost:8081/api/order/parseOrder. I've tried using some options like:
response.redirect('/parseOrder')
response.redirect('order/parseOrder')
response.redirect('api/order/parseOrder')
next('order/parseOrder')
But I cannot make the redirection work fine, so I've thought to change the /ftp/importFiles request to the order router, but I want to keep it separately. Is there any solution to redirect from one router to another router?
What you are actually asking to do is not a redirect. A redirect tells the calling client that the URL they requested does not have the resource they want and instead, they should ask for a different resource by sending an http request to a different URL.
That's not what you're trying to do. You are trying to use the functionality from a different route in the processing of the current route. You want to return a result from the current route. There are a couple ways to accomplish that.
Make an HTTP request to your own server. You can literally make an http request to your own web server and get the response from the other route using http.request()
or a higher level library such as node-fetch()
or got()
or axios()
.
Factor common code into a new function and call it both places. Oou can take the functionality that you want from the other route and factor that functionality into a common shared function that you can just call from both routes that want to use that functionality. Then, rather than make a new http request to your own server, you just call a Javascript function that does the kind of processing you want and get the result and you can use that function wherever you need/want it.
I nearly always recommend factoring common code into a shared function as it's ultimately more flexible.