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'));
It's not really server caching. It's because you are registering middleware inside a closure and thus those closure variables (like arr) are retained for the next invocation of the middleware. In addition, you're registering the middleware over and over (a new one each time /test is hit).
When you register app.use() inside an app.get() that means that every time you hit the /test route, you will add another duplicate app.use() handler. They will accumulate over time and the same middleware will get run multiple times for for the same request, retaining the previous value for arr from when it was originally registered, but each with their own value for that array.
The general solution here is to NOT register app.use() inside of app.get() because you only want one handler - you don't want them to accumulate.
It's unclear what you're trying to accomplish with your app.use('/data/, ...) middleware. It is clear that your current structure is wrong, but without understanding what you were trying to do with that, it's not clear exactly how it should be written. The usual function of middleware is to be registered once during the initialization of the server and never inside a request handler.
If you're trying to respond to your ajax call:
$.get('/data').done(function(response){...}
Then, you would want an app.get('/data', ...) at the top level of your app module to make that work.
Please explain what the arr.push() is supposed to accomplish for us to help in any more detail.