express middleware is executed twice












0














I wrote a middle ware that update some variable that I have in cache, so if the data is supposed to be expired it will updated but actually is happening twice and is not chrome, I'm using firefox.
This is my server js file(i commented mustache express as templates to be sure that it's not because of it):



const express = require('express') ;

const path = require('path');
var mustacheExpress = require('mustache-express');
var request = require('request');
var {updateAllDecks} = require('./utils/deck-request');
var cache = require('memory-cache');

const port = process.env.PORT || 3000;
var app = express();

// Register '.html' extension with The Mustache Express
app.engine('html', mustacheExpress());
app.set('view engine','mustache');

app.set('views', __dirname + '/views');

//const publicPath = path.join(__dirname, '/public');
//app.use('/', express.static(publicPath));

app.use(function (req, res, next) {
debugger;
updateAllDecks(next);
})

app.get('/', (req, res) => {
res.send('hola');
});

app.listen(port, () => {
console.log(`Server is up on port ${port}`);
});


So when I go to '/' through the browser updateAllDecks() should be called:



var rp = require('request-promise-native');
var cache = require('memory-cache');
var {Deck} = require('../classes/deck');
var cacheDeck = require('./cache-decks');
var moment = require('moment');


var updateDeck = async (set,resolve) => {
//console.log(`${cacheDeck.getCachedExpirationDate(set)} > ${moment(Date.now()).unix()}`);

if (cacheDeck.getCachedExpirationDate(set) > moment(Date.now()).unix()) {
//let deck = await getDeckCached(set);
console.log('Cached Deck Back');
resolve();

} else {
let url = `https://playartifact.com/cardset/${set}/`;
console.log('Getting URL');
response = await rp({url:url, json: true});
var deck = new Deck(set, response.expire_time);
getDeckRequest(deck,response,resolve)

}


}

var getDeckRequest = async (deck, body,resolve) => {
console.log('Caching deck', deck);
response = await rp({url:body.cdn_root + body.url.substring(1), json: true});
deck.setName(response.card_set.set_info.name.english);
deck.setCards(response.card_set.card_list);
cacheDeck.addDeck(deck);
console.log(cacheDeck.getCachedDecksNames());
resolve();

}

var getDeckCached = (id) => {
return new Promise((resolve,reject) => {
resolve(cacheDeck.getCachedDeckById(id));
});
}

var updateAllDecks = (callback) => {

let decks = [0,1];
var request = decks.map((deck) => {
return new Promise( (resolve) => {
updateDeck(deck,resolve);
});

});

Promise.all(request).then(() => {
callback();
console.log('Finished');
});
};

module.exports = {updateAllDecks}


The callback(); in the updateAllDecks() Function is the next() call to advance to show the page.










share|improve this question
























  • Hi @Roberto, it seems that you are from Chile, and me too :) ...what I think it's the cause of that issue are some misconceptions on how to serve nodejs content. You are using express and http together and you shouldn't. You should use express or http, since express uses the http module under the hood. You should have app.listen and that's it. Please take a look at this Q&A for more clarification: stackoverflow.com/questions/35167824/…
    – Hackerman
    Nov 21 '18 at 19:56










  • Also developer.mozilla.org/es/docs/Learn/Server-side/Express_Nodejs/…
    – Hackerman
    Nov 21 '18 at 19:57






  • 1




    @Hackerman si te entiendo perfectamente y lo modifiqué solo para usar express y continua ejecutándose 2 veces.
    – Roberto Matus
    Nov 21 '18 at 20:16






  • 1




    @Hackerman still, i'm going to try adding a simple middleware, maybe it has something to do with promises and next is being called twice. The game looks amazing looking forward for next week launch!
    – Roberto Matus
    Nov 21 '18 at 20:31






  • 1




    @Hackerman found it!! it was a call to a favicon, thank you a lot for your time
    – Roberto Matus
    Nov 22 '18 at 23:11
















0














I wrote a middle ware that update some variable that I have in cache, so if the data is supposed to be expired it will updated but actually is happening twice and is not chrome, I'm using firefox.
This is my server js file(i commented mustache express as templates to be sure that it's not because of it):



const express = require('express') ;

const path = require('path');
var mustacheExpress = require('mustache-express');
var request = require('request');
var {updateAllDecks} = require('./utils/deck-request');
var cache = require('memory-cache');

const port = process.env.PORT || 3000;
var app = express();

// Register '.html' extension with The Mustache Express
app.engine('html', mustacheExpress());
app.set('view engine','mustache');

app.set('views', __dirname + '/views');

//const publicPath = path.join(__dirname, '/public');
//app.use('/', express.static(publicPath));

app.use(function (req, res, next) {
debugger;
updateAllDecks(next);
})

app.get('/', (req, res) => {
res.send('hola');
});

app.listen(port, () => {
console.log(`Server is up on port ${port}`);
});


So when I go to '/' through the browser updateAllDecks() should be called:



var rp = require('request-promise-native');
var cache = require('memory-cache');
var {Deck} = require('../classes/deck');
var cacheDeck = require('./cache-decks');
var moment = require('moment');


var updateDeck = async (set,resolve) => {
//console.log(`${cacheDeck.getCachedExpirationDate(set)} > ${moment(Date.now()).unix()}`);

if (cacheDeck.getCachedExpirationDate(set) > moment(Date.now()).unix()) {
//let deck = await getDeckCached(set);
console.log('Cached Deck Back');
resolve();

} else {
let url = `https://playartifact.com/cardset/${set}/`;
console.log('Getting URL');
response = await rp({url:url, json: true});
var deck = new Deck(set, response.expire_time);
getDeckRequest(deck,response,resolve)

}


}

var getDeckRequest = async (deck, body,resolve) => {
console.log('Caching deck', deck);
response = await rp({url:body.cdn_root + body.url.substring(1), json: true});
deck.setName(response.card_set.set_info.name.english);
deck.setCards(response.card_set.card_list);
cacheDeck.addDeck(deck);
console.log(cacheDeck.getCachedDecksNames());
resolve();

}

var getDeckCached = (id) => {
return new Promise((resolve,reject) => {
resolve(cacheDeck.getCachedDeckById(id));
});
}

var updateAllDecks = (callback) => {

let decks = [0,1];
var request = decks.map((deck) => {
return new Promise( (resolve) => {
updateDeck(deck,resolve);
});

});

Promise.all(request).then(() => {
callback();
console.log('Finished');
});
};

module.exports = {updateAllDecks}


The callback(); in the updateAllDecks() Function is the next() call to advance to show the page.










share|improve this question
























  • Hi @Roberto, it seems that you are from Chile, and me too :) ...what I think it's the cause of that issue are some misconceptions on how to serve nodejs content. You are using express and http together and you shouldn't. You should use express or http, since express uses the http module under the hood. You should have app.listen and that's it. Please take a look at this Q&A for more clarification: stackoverflow.com/questions/35167824/…
    – Hackerman
    Nov 21 '18 at 19:56










  • Also developer.mozilla.org/es/docs/Learn/Server-side/Express_Nodejs/…
    – Hackerman
    Nov 21 '18 at 19:57






  • 1




    @Hackerman si te entiendo perfectamente y lo modifiqué solo para usar express y continua ejecutándose 2 veces.
    – Roberto Matus
    Nov 21 '18 at 20:16






  • 1




    @Hackerman still, i'm going to try adding a simple middleware, maybe it has something to do with promises and next is being called twice. The game looks amazing looking forward for next week launch!
    – Roberto Matus
    Nov 21 '18 at 20:31






  • 1




    @Hackerman found it!! it was a call to a favicon, thank you a lot for your time
    – Roberto Matus
    Nov 22 '18 at 23:11














0












0








0







I wrote a middle ware that update some variable that I have in cache, so if the data is supposed to be expired it will updated but actually is happening twice and is not chrome, I'm using firefox.
This is my server js file(i commented mustache express as templates to be sure that it's not because of it):



const express = require('express') ;

const path = require('path');
var mustacheExpress = require('mustache-express');
var request = require('request');
var {updateAllDecks} = require('./utils/deck-request');
var cache = require('memory-cache');

const port = process.env.PORT || 3000;
var app = express();

// Register '.html' extension with The Mustache Express
app.engine('html', mustacheExpress());
app.set('view engine','mustache');

app.set('views', __dirname + '/views');

//const publicPath = path.join(__dirname, '/public');
//app.use('/', express.static(publicPath));

app.use(function (req, res, next) {
debugger;
updateAllDecks(next);
})

app.get('/', (req, res) => {
res.send('hola');
});

app.listen(port, () => {
console.log(`Server is up on port ${port}`);
});


So when I go to '/' through the browser updateAllDecks() should be called:



var rp = require('request-promise-native');
var cache = require('memory-cache');
var {Deck} = require('../classes/deck');
var cacheDeck = require('./cache-decks');
var moment = require('moment');


var updateDeck = async (set,resolve) => {
//console.log(`${cacheDeck.getCachedExpirationDate(set)} > ${moment(Date.now()).unix()}`);

if (cacheDeck.getCachedExpirationDate(set) > moment(Date.now()).unix()) {
//let deck = await getDeckCached(set);
console.log('Cached Deck Back');
resolve();

} else {
let url = `https://playartifact.com/cardset/${set}/`;
console.log('Getting URL');
response = await rp({url:url, json: true});
var deck = new Deck(set, response.expire_time);
getDeckRequest(deck,response,resolve)

}


}

var getDeckRequest = async (deck, body,resolve) => {
console.log('Caching deck', deck);
response = await rp({url:body.cdn_root + body.url.substring(1), json: true});
deck.setName(response.card_set.set_info.name.english);
deck.setCards(response.card_set.card_list);
cacheDeck.addDeck(deck);
console.log(cacheDeck.getCachedDecksNames());
resolve();

}

var getDeckCached = (id) => {
return new Promise((resolve,reject) => {
resolve(cacheDeck.getCachedDeckById(id));
});
}

var updateAllDecks = (callback) => {

let decks = [0,1];
var request = decks.map((deck) => {
return new Promise( (resolve) => {
updateDeck(deck,resolve);
});

});

Promise.all(request).then(() => {
callback();
console.log('Finished');
});
};

module.exports = {updateAllDecks}


The callback(); in the updateAllDecks() Function is the next() call to advance to show the page.










share|improve this question















I wrote a middle ware that update some variable that I have in cache, so if the data is supposed to be expired it will updated but actually is happening twice and is not chrome, I'm using firefox.
This is my server js file(i commented mustache express as templates to be sure that it's not because of it):



const express = require('express') ;

const path = require('path');
var mustacheExpress = require('mustache-express');
var request = require('request');
var {updateAllDecks} = require('./utils/deck-request');
var cache = require('memory-cache');

const port = process.env.PORT || 3000;
var app = express();

// Register '.html' extension with The Mustache Express
app.engine('html', mustacheExpress());
app.set('view engine','mustache');

app.set('views', __dirname + '/views');

//const publicPath = path.join(__dirname, '/public');
//app.use('/', express.static(publicPath));

app.use(function (req, res, next) {
debugger;
updateAllDecks(next);
})

app.get('/', (req, res) => {
res.send('hola');
});

app.listen(port, () => {
console.log(`Server is up on port ${port}`);
});


So when I go to '/' through the browser updateAllDecks() should be called:



var rp = require('request-promise-native');
var cache = require('memory-cache');
var {Deck} = require('../classes/deck');
var cacheDeck = require('./cache-decks');
var moment = require('moment');


var updateDeck = async (set,resolve) => {
//console.log(`${cacheDeck.getCachedExpirationDate(set)} > ${moment(Date.now()).unix()}`);

if (cacheDeck.getCachedExpirationDate(set) > moment(Date.now()).unix()) {
//let deck = await getDeckCached(set);
console.log('Cached Deck Back');
resolve();

} else {
let url = `https://playartifact.com/cardset/${set}/`;
console.log('Getting URL');
response = await rp({url:url, json: true});
var deck = new Deck(set, response.expire_time);
getDeckRequest(deck,response,resolve)

}


}

var getDeckRequest = async (deck, body,resolve) => {
console.log('Caching deck', deck);
response = await rp({url:body.cdn_root + body.url.substring(1), json: true});
deck.setName(response.card_set.set_info.name.english);
deck.setCards(response.card_set.card_list);
cacheDeck.addDeck(deck);
console.log(cacheDeck.getCachedDecksNames());
resolve();

}

var getDeckCached = (id) => {
return new Promise((resolve,reject) => {
resolve(cacheDeck.getCachedDeckById(id));
});
}

var updateAllDecks = (callback) => {

let decks = [0,1];
var request = decks.map((deck) => {
return new Promise( (resolve) => {
updateDeck(deck,resolve);
});

});

Promise.all(request).then(() => {
callback();
console.log('Finished');
});
};

module.exports = {updateAllDecks}


The callback(); in the updateAllDecks() Function is the next() call to advance to show the page.







javascript node.js express






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 20:11







Roberto Matus

















asked Nov 21 '18 at 19:45









Roberto MatusRoberto Matus

13




13












  • Hi @Roberto, it seems that you are from Chile, and me too :) ...what I think it's the cause of that issue are some misconceptions on how to serve nodejs content. You are using express and http together and you shouldn't. You should use express or http, since express uses the http module under the hood. You should have app.listen and that's it. Please take a look at this Q&A for more clarification: stackoverflow.com/questions/35167824/…
    – Hackerman
    Nov 21 '18 at 19:56










  • Also developer.mozilla.org/es/docs/Learn/Server-side/Express_Nodejs/…
    – Hackerman
    Nov 21 '18 at 19:57






  • 1




    @Hackerman si te entiendo perfectamente y lo modifiqué solo para usar express y continua ejecutándose 2 veces.
    – Roberto Matus
    Nov 21 '18 at 20:16






  • 1




    @Hackerman still, i'm going to try adding a simple middleware, maybe it has something to do with promises and next is being called twice. The game looks amazing looking forward for next week launch!
    – Roberto Matus
    Nov 21 '18 at 20:31






  • 1




    @Hackerman found it!! it was a call to a favicon, thank you a lot for your time
    – Roberto Matus
    Nov 22 '18 at 23:11


















  • Hi @Roberto, it seems that you are from Chile, and me too :) ...what I think it's the cause of that issue are some misconceptions on how to serve nodejs content. You are using express and http together and you shouldn't. You should use express or http, since express uses the http module under the hood. You should have app.listen and that's it. Please take a look at this Q&A for more clarification: stackoverflow.com/questions/35167824/…
    – Hackerman
    Nov 21 '18 at 19:56










  • Also developer.mozilla.org/es/docs/Learn/Server-side/Express_Nodejs/…
    – Hackerman
    Nov 21 '18 at 19:57






  • 1




    @Hackerman si te entiendo perfectamente y lo modifiqué solo para usar express y continua ejecutándose 2 veces.
    – Roberto Matus
    Nov 21 '18 at 20:16






  • 1




    @Hackerman still, i'm going to try adding a simple middleware, maybe it has something to do with promises and next is being called twice. The game looks amazing looking forward for next week launch!
    – Roberto Matus
    Nov 21 '18 at 20:31






  • 1




    @Hackerman found it!! it was a call to a favicon, thank you a lot for your time
    – Roberto Matus
    Nov 22 '18 at 23:11
















Hi @Roberto, it seems that you are from Chile, and me too :) ...what I think it's the cause of that issue are some misconceptions on how to serve nodejs content. You are using express and http together and you shouldn't. You should use express or http, since express uses the http module under the hood. You should have app.listen and that's it. Please take a look at this Q&A for more clarification: stackoverflow.com/questions/35167824/…
– Hackerman
Nov 21 '18 at 19:56




Hi @Roberto, it seems that you are from Chile, and me too :) ...what I think it's the cause of that issue are some misconceptions on how to serve nodejs content. You are using express and http together and you shouldn't. You should use express or http, since express uses the http module under the hood. You should have app.listen and that's it. Please take a look at this Q&A for more clarification: stackoverflow.com/questions/35167824/…
– Hackerman
Nov 21 '18 at 19:56












Also developer.mozilla.org/es/docs/Learn/Server-side/Express_Nodejs/…
– Hackerman
Nov 21 '18 at 19:57




Also developer.mozilla.org/es/docs/Learn/Server-side/Express_Nodejs/…
– Hackerman
Nov 21 '18 at 19:57




1




1




@Hackerman si te entiendo perfectamente y lo modifiqué solo para usar express y continua ejecutándose 2 veces.
– Roberto Matus
Nov 21 '18 at 20:16




@Hackerman si te entiendo perfectamente y lo modifiqué solo para usar express y continua ejecutándose 2 veces.
– Roberto Matus
Nov 21 '18 at 20:16




1




1




@Hackerman still, i'm going to try adding a simple middleware, maybe it has something to do with promises and next is being called twice. The game looks amazing looking forward for next week launch!
– Roberto Matus
Nov 21 '18 at 20:31




@Hackerman still, i'm going to try adding a simple middleware, maybe it has something to do with promises and next is being called twice. The game looks amazing looking forward for next week launch!
– Roberto Matus
Nov 21 '18 at 20:31




1




1




@Hackerman found it!! it was a call to a favicon, thank you a lot for your time
– Roberto Matus
Nov 22 '18 at 23:11




@Hackerman found it!! it was a call to a favicon, thank you a lot for your time
– Roberto Matus
Nov 22 '18 at 23:11












1 Answer
1






active

oldest

votes


















0














Added this line of code in the middleware function to know what was the call.



console.log(req.method, req.path)


Turns out that was the call from the browser to the server to get the favicon that made express to call the middleware.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53419482%2fexpress-middleware-is-executed-twice%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Added this line of code in the middleware function to know what was the call.



    console.log(req.method, req.path)


    Turns out that was the call from the browser to the server to get the favicon that made express to call the middleware.






    share|improve this answer


























      0














      Added this line of code in the middleware function to know what was the call.



      console.log(req.method, req.path)


      Turns out that was the call from the browser to the server to get the favicon that made express to call the middleware.






      share|improve this answer
























        0












        0








        0






        Added this line of code in the middleware function to know what was the call.



        console.log(req.method, req.path)


        Turns out that was the call from the browser to the server to get the favicon that made express to call the middleware.






        share|improve this answer












        Added this line of code in the middleware function to know what was the call.



        console.log(req.method, req.path)


        Turns out that was the call from the browser to the server to get the favicon that made express to call the middleware.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 23 '18 at 12:13









        Roberto MatusRoberto Matus

        13




        13






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53419482%2fexpress-middleware-is-executed-twice%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            What visual should I use to simply compare current year value vs last year in Power BI desktop

            Alexandru Averescu

            Trompette piccolo