Node.js 有没有办法在一个路由中读取变量并在另一个路由中传递该值?

Node.js 有没有办法在一个路由中读取变量并在另一个路由中传递该值?,node.js,Node.js,我正在努力学习NodeJS。我想创建一个变量,我想在一个路由中读取它,然后以某种方式将它传递给另一个路由。我创建了一个全局变量,并尝试了相同的方法。但它给了我一个未定义的值。请帮忙 const http = require('http'); var fs = require('fs'); const readline = require('readline').createInterface({ input: process.stdin, output: process.stdo

我正在努力学习NodeJS。我想创建一个变量,我想在一个路由中读取它,然后以某种方式将它传递给另一个路由。我创建了一个全局变量,并尝试了相同的方法。但它给了我一个未定义的值。请帮忙

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);
})
consthttp=require('http');
var fs=需要('fs');
const readline=require('readline')。createInterface({
输入:process.stdin,
输出:process.stdout
});
常数端口=5000;
函数requestHandler(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
日志(“URL:,请求URL”);
var url=req.url;
var n;
如果(url=='/')){
res.write('这是需要输入n的输入的主页面');
readline.question('请输入n的值,以便我可以告诉您前n个素数:',maxCount=>{
log(“maxCount的值为:”,maxCount);
n=最大计数;
});
res.end();//结束响应
}else if(url=='/result'){
res.write(“联系我们页面”);
log(“此处n的值为:”,n);
res.end();
}否则{
res.write('您试图转到一个不存在的页面');
res.end();
}
}
const server=http.createServer(requestHandler);
侦听(端口、函数(错误){
如果(错误){
控制台日志(err);
返回;
}
log(“服务器已启动并在端口:”,端口上运行);
})

这是因为您的
requestHandler
函数在每个请求上都会运行,每次运行时,您都会重新定义
n
-变量。因此,对于交叉请求,没有
n
变量的概念

n
-变量移到
requestHandler
函数之外将完成您尝试执行的操作

除此之外,我强烈建议您:

  • 创建web服务器时不要使用stdin
  • 使用另一种机制跨请求存储变量。也许是个好的开始

我认为你不应该试图重写人们所做的一切。我建议您对Nodejs()使用express-web框架