简体   繁体   中英

Extracting extra parameters from HTTP request

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM