U
U
unituser2020-07-28 13:05:12
MySQL
unituser, 2020-07-28 13:05:12

How can I bring this into Middleware ExpressJS?

Good afternoon, I’ve been thinking for a very long time, how can I put this in middleware so as not to write it on every page?
You do not need to be logged in to access these pages. The user can access them without authorization, but if the user is authorized, certain data is displayed from the database.

router.get('/', (req, res) => {

    if (req.isAuthenticated()) {

        id = req.user.id

        const sql = 'SELECT * FROM users WHERE steamid = ' + id + ' || vkontakteid = ' + id + ' || googleid = ' + id + ''

        pool.query(sql, function(err, result) {

            if (err) return console.log(err)

            res.render('index', {
                titlePage: 'Index',
                data: result
            })

        })

    } else {
        res.render('index', {
            titlePage: 'Index'
        })
    }
})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-07-28
@unituser

something like that, probably got confused in parentheses

router.get('/', getData, (req, res) => {
  res.render('index', {
    titlePage: 'Index'
    // или data или null
    data: req.data
  })
})


// middleware
function getData(req, res, next) {
    req.data = null

    if (!req.isAuthenticated()) return next()

    // auth ok
    const id = req.user.id
    const sql = 'SELECT * FROM users WHERE steamid = ' + id + ' || vkontakteid = ' + id + ' || googleid = ' + id + ''

    pool.query(sql, function(err, result) {
        if(err) return next()

        req.data = result
        next()
    })
  
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question