How to pass parameter to routes? - node.js

I am using Nodejs .
Server.js
app.get('/dashboard/:id', routes.dashboard);
Routes / index.js
exports.dashboard = function(req, res){
}
I want to be able to pass the 'id' variable from app.js to the dashboard function . How do I go about doing this ?

Assuming ExpressJS, you shouldn't need to pass it.
For each parameter placeholder (like :id), req.params should have a matching property holding the value:
exports.dashboard = function (req, res) {
console.log(req.params.id);
};
Though, this assumes the requested URL matches the route by verb and pattern.

Just ensure that your GET call from the client is something like this: /dashboard/12345.
12345 is the id you want to pass to dashboard.
So, you can access it like this in server:
exports.dashboard = function(req, res){
var id = req.params.id;
console.log('ID in dashboard: %s', id);
}

Related

first portion of route url is not included

I have a route where I built two GET APIs. I would like one to redirect from /download to /zip all while passing a parameter. The problem is I am getting a 404 for some reason the routes url is not being included in the redirect()
Here are the APIs.
// respond with xml from from static folder
router.get('/zip/:id', function (req, res) {
fileName = req.params.id
});
router.get('/download', function (req, res, next) {
var id = req.query.id
res.redirect('/zip?id='+ id);
});
module.exports = router;
I get a 404 when testing the URL:
localhost:8000/rest/pluto/v1/plugin/download?id=networktool
I am thinking it might be how I have the middleware setup but not real sure. I'm still new to node/express.
You are redirecting to a route that isn't actually defined. With your /zip/:id route definition:
router.get('/zip/:id', function (req, res) {
var fileName = req.params.id
});
The way that is defined, you have to have id information in the URL itself, so while the following routes would work:
/zip/networktool
/zip/1234
these routes would not:
/zip
/zip?id=networktool
/zip?id=1234
because Express is looking for the id to be built into the route itself. So you can do one of two things. You can either change your redirect to:
router.get('/download', function (req, res, next) {
res.redirect('/zip/'+ req.query.id);
});
or, you can modify your /zip route to make the id parameter optional with ?:
router.get('/zip/:id?', function (req, res) {
var fileName = (req.params.id) ? req.params.id : req.query.id;
});
I would recommend the first option, as the latter optional parameter only makes your zip route more complicated and require extra handling of whether id is actually passed to your route.
The path /zip/:id is expecting a path parameter not a query parameter.
You should redirect like this
res.redirect('/zip/'+ id);

Resolve URL with info from URL parameters

I've been thrown at a Node.js project at work and I'm not a Node developer. My first task is to resolve urls to stores from a URL parameter. Here's what needs to happen:
The original URL contains the URL parameter "siteName" as here:
https://example.com/s/Store/?siteName=SLUG
The above url with parameter would then resolve to
https://example.com/s/Store/SLUG
This project is running on Express ^4.3.0.
I've been diving into the Node docs but I'm not sure even where to start.
I would suggest you look into Express
The solution to your problem is easy. Firstly, you'd need to establish a middleware to listen to requests for /s/Stores route. Then parse the query params and get the value for the siteName key. Finally use the res.redirect method to run the logic for /s/Store/SLUG route.
The solution would look something like
app.get('/s/Stores', (req, res, next) => {
const query = req.query;
const siteName = query.siteName;
res.redirect('/s/Stores/' + siteName);
});
app.get('/s/Stores/:siteName', (req, res, next) => {
const siteName = req.params.siteName;
if (siteName === 'SLUG') {
// do something
}
// do something else
});
Assuming Store route is the page you want to see with parameters, if you are using url query parameters, use first example and it matches your first question.
If you are trying to get url parameters without query, use second example.
//https://example.com/s/Store/?siteName=SLUG
app.get('/Store', function(req, res){
let siteName = req.query.siteName,
});
//https://example.com/s/Store/SLUG/
app.get('/Store/:slug', function (req, res) {
let slug = req.params.slug,
});

How to modify variable inside one route matching and use that modified value as route configuration for next routes?

How to modify variable inside one route matching and use that modified value as route configuration for next routes?
// app.js
var rootprefix = 'test';
app.get('/' + rootPrefix', function (req, res) {
....
**rootprefix = 'test_updated';**
});
app.post('/' + **rootPrefix** + '/api/v4/upload/', function (req, res) {
....
....
....
});
Here for post request, I want to match rootPrefix updated value 'test_updated' to instead of original value 'test'.
//post '/test_updated' - should match
//post 'test' - should not match
Routes are established once the app is started, therefore route configuration cannot be changed once the app is on.
What you can to is pass a parameter and check if the passed parameter matches the changed prefix like this:
app.get('/' + rootPrefix', function (req, res) {
....
**rootprefix = 'test_updated';**
});
app.post(':prefix/api/v4/upload/', function (req, res) {
if (req.params.prefix !== rootprefix) res.send(200); //or 500 depends on you
....
....
});

Passing a variable to an external route

I have a Node js and Express web app.
My app.js looks like
var pages_route = require('./route/pages');
/*
---------------------
------ ROUTE --------
---------------------
*/
app.get('/', pages_route.index);//home
My route/pages.js looks like
exports.index = function(req, res){
res.render( 'home.ejs');
};
I'm trying to pass the view name for every route from the app.js file like the follow:
app.get('/', pages_route.index), template = 'home';
In route/pages.js
exports.index = function(req, res){
res.render( template + '.ejs');
};
This solution works fine for a single route, but when I create more than one like
app.get('/', pages_route.index), template = 'home';
app.get('/custompage', pages_route.custom), template = 'skeleton';
The app will take the last view name passed for all the routes, in this case the view "skeleton" will be printed for all my routes.
I don't want to create a different instance for every route like template1, template2, template3 etc.. I just want to find a solution similar to my example.
Thank you!!
Express doesn't give you just req and res like native node. It also gives you next
Next allows you build middleware, functions that occur as part of handling the request, but don't necessarily end the request.
Here's an example for your use case:
// middleware
function setTemplate (template) {
return function applyTemplate (req, res, next) {
req.template = template;
next();
};
}
// route
app.get('/', setTemplate('home'), pages_route.index);
// handler
exports.index = function (req, res) {
res.render(req.template + '.ejs');
};

Express routes parameter conditions

I have a route on my Express app that looks like this:
app.get('/:id', function (request, response) {
…
});
The ID will always be a number. However, at the moment this route is matching other things, such as /login.
I think I want two things from this:
to only use this route if the ID is a number, and
only if there isn't a route for that specific paramater already defined (such as the clash with /login).
Can this be done?
Expanding on Marius's answer, you can provide the regex AND the parameter name:
app.get('/:id(\\d+)/', function (req, res){
// req.params.id is now defined here for you
});
Yes, check out http://expressjs.com/guide/routing.html and https://www.npmjs.com/package/path-to-regexp (which express uses). An untested version that may work is:
app.get(/^(\d+)$/, function (request, response) {
var id = request.params[0];
...
});
You can use:
// /12345
app.get(/\/([^\/]+)\/?/, function(req, res){
var id = req.params[0];
// do something
});
or this:
// /post/12345
app.get(/\/post\/([^\/]+)\/?/, function(req, res){
var id = req.params[0];
// do something
});

Resources