node.js - 有没有办法在一条路线中读取变量并在另一条路线中传递该值?
问题描述
我正在尝试学习节点 js。我想创建一个变量,我想在一条路线中读取它并以某种方式将它传递给另一条路线。我创建了一个全局变量并尝试相同。但它给了我未定义的价值。请帮忙。
const http = require('http');
var fs = require('fs');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
const port = 5000;
function requestHandler(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
console.log("URL: ", req.url);
var url = req.url;
var n;
if(url ==='/'){
res.write('<h1 style="margin-top: 10vh; margin-left: 10vw;">This is the main page where you need to enter the input for n<h1>');
readline.question('Please enter the value of n, so that I can tell you first n prime numbers: ', maxCount => {
console.log("The value of maxCount is: ", maxCount);
n = maxCount;
});
res.end(); //end the response
}else if(url ==='/result'){
res.write('<h1>contact us page<h1>');
console.log("The value of n here is: ", n);
res.end();
}else{
res.write('<h1>You are trying to go to a page which does not exist <h1>');
res.end();
}
}
const server = http.createServer(requestHandler);
server.listen(port, function(err){
if(err){
console.log(err);
return;
}
console.log("Server is up and running on port: ", port);
})
解决方案
那是因为您的requestHandler
函数在每个请求上运行,并且每次运行时,您都重新定义了您的n
-variable。所以,交叉请求,没有n
变量的概念。
将您的n
-variable移到requestHandler
函数之外将完成您正在尝试做的事情。
除此之外,我强烈建议您:
stdin
在创建 Web 服务器时不要使用。- 使用另一种机制来存储变量交叉请求。express-session可能是一个好的开始。
推荐阅读
- google-apps-script - Browser.msgBox() 在打开多个框时超时(Google 表格)
- php - 如何从表 2 中选择数据与表 1 连接
- mongodb - Mongo 查询:GraphLookup 或 Aggregate
- excel - Excel公式计算签到时间
- consul - Consul 1.2.1 在命令参数中使用管道定义健康检查
- node.js - Laravel vue js npm run watch 只工作一次
- javascript - 仅在加载时为项目设置动画
- python - 当每个列表可能有不同数量的成员时,如何将列表中的一列拆分为新列?
- reactjs - 即使在 DOM 中,如何使组件在 UI 中不可见?
- powerbi - Power BI - 增量刷新