var payload = {
type: 'PAYLOAD'
};
app.get('/location', function(req, res) {
res.sendFile(__dirname + '/public/pages/locations.html',payload);
});
您好,我是expressjs、javascript和node的新手,我无法设法通过app.get传递数据,我想要做的是将有效负载的类型作为GET参数(所以要查看/locations?type=type_of_location ),或者至少能够从页面locations.html的javascript访问它。
预先感谢您的帮助
最佳答案
如果您请求 /locations?type=type_of_location
,那么您可以使用 req.query.type
访问该 type
数据,因为 req.query
对象有您需要的数据。
更新:
首先在您的服务器上执行此操作:顺便说一句,将 /locations?type=type_of_location
发送到客户端的唯一方法是重定向他,然后发送文件。
app.get('/location', function(req, res) {
if(!req.query.type)
res.redirect('/location?type=' + payload);
else
res.sendFile(__dirname + '/public/pages/locations.html',payload);
});
如果您想执行相反的操作,请将 /locations?type=type_of_location
发送到客户端并提取 type=type_of_location
的值,然后您可以使用 javascript 执行此操作使用 window.location.search
返回 ?type=type_of_location
。
然后在您的客户端 javascript 上执行此操作:然后必须使用正则表达式处理该结果,例如:
let query = window.location.search;
let typeValue = /type=(.*)/.exec(query)[1]; // Extract the value
关于javascript - 在expressjs中传递get参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44342052/