Friday, 7 April 2017

Express app.use refresh behavior

I'm using Express with Node.js and am quite confused about refreshing behavior. Upon refresh of /test, it seems like something is cached server-side when it hits app.use because the array length is nonzero (see sample code below). I would expect the array length to reset to zero since I'm hitting /testagain when I'm refreshing the browser.

Does app.use cache things by default? How does Express middleware work in terms of refresh? I couldn't find anything that explained this clearly in the Express 4.14 docs.

==================

Browser Endpoint: localhost:8000/test

Client:

$.get('/data').done(function(response){...}

Route:

module.exports = function(app) {
  app.get('/test', function(req,res) {
    var arr =[];
    app.use('/data', function(req,res, next) {
      console.log(arr.length); // this is nonzero on refresh
      arr.push(/* some stuff*/);
      res.send({"arr": arr});
    }
   res.render('test.html')
  }
}

Server:

var express = require('express');
var app = express();

require('./routes/route')(app);
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);

var server = app.listen(8000, function() {
    console.log("server started 8000");
});
app.use(express.static(__dirname + '/public'));



via Bethany