Reputation: 609
Let's say I send to a Node Server a request to get a JS file:
<script src="/blabla.js" id="545234677">
and on my Node side:
app.get('/blabla.js', function(req, res, next) {
console.log(req.params.id); //undefined
res.setHeader('content-type', 'text/javascript');
res.render('blabla'); //default
});
and finally I have this template file blabla.ejs:
var id = <%= id %>
Now, I am trying to get that id para but it's showing undefined. I am using Express and EJS, and once I get that ID I want to manipulate an EJS file and send back a JS file which adapts itself according to the ID my node app received. Thank you.
Upvotes: 0
Views: 45
Reputation: 448
How about changing your script to
<script src="[filename][id].js"></script>
EG:<script src="blabla123.js"></script>
then you can do something using regular expressions like
app.get(/^\/([a-zA-z]*)([0-9]*).js/,function(req,res,next){
var fileName = req.params['0'],
id = req.params['1'];
console.log(fileName);
console.log(id);
// Now since you have both fileName and id as you required, you can
// use it to dynamically serve the content
// if(file=='' && id==''){//logic}
// If you want static file Name, modify the regular expression accordingly
})
Just modify the regular expression in above example as per your need and its done. Currently the above regex matches for any of
/.js
/[numeric].js
/[alphabet].js
/[alphabet][numerals].js
I hope this helps.
Upvotes: 1
Reputation: 6783
The way to do this would probably be like this - In your HTML you would request the JS file like so:
<script src="/blabla.js?id=545234677">
And then for express you would do the following:
app.get('/blabla.js', function(req, res, next) {
console.log(req.query.id);
res.setHeader('content-type', 'text/javascript');
// Pass id into the renderer
res.render('blabla', {id: req.query.id}); //default
});
Although rendering is normally used to render HTML. There is probably a better way to do what you want in a more elegant way.
Note: req.params
would work, but would make the url look like /blabla.js/545234677
. See the documentation on req.params.
Upvotes: 3