Node.js中Express路由变量页面刷新后为何持续保留?
Why does my Express route's variable persist across requests?
Let's start with your code for context:
const express = require('express'); const route = express.Router() ; let a = 0; route.get('/', (req,res)=> { a++; res.send(`hello api we are here! ${a}`) }) module.exports = route;
You noticed that the first visit to localhost shows hello api we are here! 1, and every refresh increments the number — but you expected the server to reload from scratch for each browser connection. Here's what you're missing:
- Your Express server runs as a single, long-lived process: Once you start your server (e.g., with
node server.js), it stays alive in memory until you manually stop it. It doesn't shut down and restart for every incoming request — that would be terribly inefficient. - Module-level variables are initialized once: Your
let a = 0is declared at the top level of your route module. When the server starts up, this module is loaded one time, and theavariable is created in the module's scope. Every subsequent request to the/route reuses this same variable — it never resets to 0 unless you restart the server. - Scope determines variable lifetime: If you wanted a variable that's fresh for every request, you'd declare it inside the route handler function (like moving
let a = 0;inside the(req, res) => {...}block). But since you're tracking total requests, keepingaat the module level makes perfect sense — just remember it'll only reset when you restart your server.
In short: Your server isn't reloading for each connection. It's a persistent process that retains your module's variables in memory between requests, which is why a keeps counting up.
内容的提问来源于stack exchange,提问作者aryan
相关产品推荐
相关产品推荐

