[英]Express, how to pass variables from routes to JS file that is in the client side
I have an Express project that has client-side javascript in a separate file that generates a graph. 我有一个Express项目,它在一个生成图形的单独文件中有客户端javascript。 I am trying to pass variables from the express routes to this javascript file so the graph can be drawn. 我试图将变量从快速路由传递到此javascript文件,以便绘制图形。 I have tried the code below but I am getting following error. 我已经尝试了下面的代码,但我收到了以下错误。
Error: Cannot find module 'js' 错误:找不到模块'js'
app.get('/users', function(req, res) {
res.render(path.join(__dirname, '../views/js/users_chart.js'), {
'users': users
});
});
I think it'd be helpful for you to review the Express documentation for res.render and serving static files 我认为查看res.render和提供静态文件的Express文档会很有帮助
You can't render JS files. 您无法呈现JS文件。
It appears you want to serve your static user_chart.js
with 您似乎想要使用静态user_chart.js
/* server.js */
app.set('view engine', 'ejs');
app.register('.html', require('ejs'));
// serve your js statically
app.use('/js', path.join(__dirname, '../views/js/users_chart.js')
app.get('/users', function(req, res) {
// pass variable to html page
res.render('users.html', {
'users': users
});
});
// in users.html
<script type="text/javascript" src="/js/users_chart.js">
After receiving great help, found out a solution. 在得到很大的帮助后,找到了解决方案。
In order to have a javascript file in the client side that would receive the variable from the routes, I had to send the variable in JSON from the routes file to the javascript file the client side. 为了在客户端有一个javascript文件,它将从路由接收变量,我不得不将路径文件中的JSON变量发送到客户端的javascript文件。 I used XMLHttpRequest in order to receive the JSON in the javascript file of the client side. 我使用XMLHttpRequest以便在客户端的javascript文件中接收JSON。
Bellow is the code for users_graph.js which is the client side javascript file. Bellow是users_graph.js的代码,它是客户端javascript文件。
var xmlhttp = new XMLHttpRequest();
var url = "/users";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var users = JSON.parse(xmlhttp.responseText).users;
// do something with the users variable that was passed by the routes
}
};
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader('Accept', 'application/json');
xmlhttp.send();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.