[英]Extracting extra parameters from HTTP request
Let's say I send to a Node Server a request to get a JS file: 假设我向节点服务器发送了获取JS文件的请求:
<script src="/blabla.js" id="545234677">
and on my Node side: 在我的Node端:
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: 最后我有这个模板文件blabla.ejs:
var id = <%= id %>
Now, I am trying to get that id para but it's showing undefined. 现在,我尝试获取该id参数,但是显示为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. 我正在使用Express和EJS,一旦获得该ID,便想处理一个EJS文件并发回一个JS文件,该文件根据我的节点应用程序收到的ID进行调整。 Thank you. 谢谢。
The way to do this would probably be like this - In your HTML you would request the JS file like so: 这样做的方式可能是这样的-在HTML中,您将请求JS文件,如下所示:
<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. 尽管渲染通常用于渲染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
. 注意: req.params
可以工作,但是会使URL看起来像/blabla.js/545234677
。 See the documentation on req.params. 请参阅有关req.params的文档 。
How about changing your script to 如何将脚本更改为
<script src="[filename][id].js"></script>
EG: <script src="blabla123.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. 我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.