javascript - Express app.use refresh behavior -


i'm using express node.js , quite confused refreshing behavior. upon refresh of /test, seems cached server-side when hits app.use because array length nonzero (see sample code below). expect array length reset 0 since i'm hitting /testagain when i'm refreshing browser.

does app.use cache things default? how express middleware work in terms of refresh? couldn't find explained in 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); // nonzero on refresh       arr.push(/* 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 server caching. it's because registering middleware inside closure , closure variables (like arr) retained next invocation of middleware. in addition, you're registering middleware on , on (a new 1 each time /test hit).

when register app.use() inside app.get() means every time hit /test route, add duplicate app.use() handler. accumulate on time , same middleware run multiple times for same request, retaining previous value arr when registered, each own value array.

the general solution here not register app.use() inside of app.get() because want 1 handler - don't want them accumulate.


it's unclear you're trying accomplish app.use('/data/, ...) middleware. clear current structure wrong, without understanding trying that, it's not clear how should written. usual function of middleware registered once during initialization of server , never inside request handler.


if you're trying respond ajax call:

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

then, want app.get('/data', ...) @ top level of app module make work.


please explain arr.push() supposed accomplish in more detail.


Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -