gpt4 book ai didi

javascript - express 中间件被执行了两次

转载 作者:行者123 更新时间:2023-11-30 11:11:35 26 4
gpt4 key购买 nike

我写了一个中间件来更新我在缓存中的一些变量,所以如果数据应该过期它会更新但实际上发生了两次并且不是 chrome,我使用的是 firefox。这是我的服务器 js 文件(我评论了 mustache express as templates 以确保它不是因为它):

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}

回调();在 updateAllDecks() 函数中是 next() 调用以推进显示页面。

最佳答案

在中间件函数中添加了这行代码以了解调用的内容。

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

原来是浏览器调用服务器获取favicon,使express调用中间件。

关于javascript - express 中间件被执行了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53419482/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com