我写了一个中间件来更新我在缓存中拥有的一些变量,因此,如果数据应该过期,它将被更新,但实际上发生了两次,而且不是chrome,我正在使用firefox。 这是我的服务器js文件(我注释了胡子表示为模板,以确保不是因为它):
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}`);
});
因此,当我通过浏览器转到“ /”时,应调用updateAllDecks():
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}
callback();在updateAllDecks()函数中,是next()调用以前进以显示页面。
答案 0 :(得分:1)
在中间件函数中添加了以下代码行,以了解调用的内容。
console.log(req.method, req.path)
事实证明,这是从浏览器到服务器的调用,以获得明确表示调用中间件的图标。