Node.js 在中首次加载页面之前设置Cookie

Node.js 在中首次加载页面之前设置Cookie,node.js,express,cookies,Node.js,Express,Cookies,有没有办法在首次进入网站之前设置cookies?现在,我在每个get操作的开头添加了以下代码: if(!req.cookies.lang) { res.cookie('lang', 'en'); res.redirect('back'); } 有没有更好的解决方案,这样就不需要在每次get开始时添加此代码?为了避免代码重复,您可以添加一个中间件,为每次get处理此问题 app.get('*', (req, res, next) => { if (!req.cook

有没有办法在首次进入网站之前设置cookies?现在,我在每个get操作的开头添加了以下代码:

if(!req.cookies.lang) {
    res.cookie('lang', 'en');
    res.redirect('back');
}

有没有更好的解决方案,这样就不需要在每次get开始时添加此代码?

为了避免代码重复,您可以添加一个中间件,为每次
get
处理此问题

app.get('*', (req, res, next) => {
    if (!req.cookies.lang) {
        res.cookie('lang', 'en');
        return res.redirect('back');
    }

    next();
});

/* get routes */
app.get('/some/route', (req, res) => {
    // No need to check cookie, it was checked by the other middleware
    // ... 
});

/* ... */

为了避免代码重复,您可以添加一个中间件来处理每个
GET

app.get('*', (req, res, next) => {
    if (!req.cookies.lang) {
        res.cookie('lang', 'en');
        return res.redirect('back');
    }

    next();
});

/* get routes */
app.get('/some/route', (req, res) => {
    // No need to check cookie, it was checked by the other middleware
    // ... 
});

/* ... */