wilson Liu
wilson Liu

Reputation: 579

where does express.js store variable value?

I found some snippets from express.js tutorials as following.

server.js

var express = require('express'),
bodyParser = require('body-parser'),
app = express();

app.use(bodyParser.urlencoded());

var names = [];

app.get('/', function(req, res){

    res.render('index.jade', { names : names });
});

app.post('/', function(req, res){

names.push(req.body.name);
res.redirect('/'); 
});

app.listen('3000',function(){

   console.log('start to listen port:3000');
})

index.jade

h1 Names

ul
    for name in names
        li=name

hr
h1 Add Name
form(method='POST')
    input(name='name')
    button Submit

As I submit some names,the names variable keeps show on the page!

Even I start a new browser and check the root page, the names variable is still exist!!!!

How does it work?

For my knowledge, HTTP is stateless. I dont think PHP could do something like this since it has been redirect, how the heck did the root page know the names variable without saving into session or cookies?

And I dont think the names variable is session or cookie in the above code.

Could someone give me some hint?Thanks!

Upvotes: 0

Views: 1273

Answers (1)

mscdex
mscdex

Reputation: 106696

You're pushing them into names, which is a variable declared in the parent scope and thus accessible by all requests. So it's not per-session or per-request, it's per-life of the server process.

Upvotes: 2

Related Questions