首页 > 解决方案 > 有没有办法在一条路线中读取变量并在另一条路线中传递该值?

问题描述

我正在尝试学习节点 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);
})

标签: node.js

解决方案


那是因为您的requestHandler函数在每个请求上运行,并且每次运行时,您都重新定义了您的n-variable。所以,交叉请求,没有n变量的概念。

将您的n-variable移到requestHandler函数之外将完成您正在尝试做的事情。

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

  • stdin在创建 Web 服务器时不要使用。
  • 使用另一种机制来存储变量交叉请求。express-session可能是一个好的开始。

推荐阅读