1

So i'm trying to send user_id to the profile page through res.redirect(). here is my login.js:

const express = require('express')
const router = express.Router()
let alert = require('alert')
const bcrypt = require('bcrypt')
const mysqlConnection = require("../utils/database")

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

    //Check if user exists in the database
    await new Promise((res, rej) => {
        var sql = "SELECT * FROM usercredentials WHERE username = ?"
        mysqlConnection.query(sql, req.body.username, (err, result) => {
            if(err) throw err
            
            //If result length is bigger than 0 then the user exists in the database
            if(result.length > 0) {
                validUsername = true
                userPassword = result[0].password
                console.log(result)
                var user_id = result.insertId
                res(result)
            } else {
                validUsername = false
                console.log(result)

                res(result)
            }
        })
    })

    //If username is valid then check if password is correct
    if (validUsername == true) {
        const validPassword = await bcrypt.compare(req.body.password, userPassword)
        if (validPassword) {
            console.log('Successful Login')
            req.session.user_id = user_id;
            res.redirect('profile.html')
        } else {
            console.log('Failed Login')
            alert('Failed Login')

            res.redirect('login.html')
        }
    } else {
        console.log('User does not exist')
        alert('User does not exist')

        res.redirect('login.html')
    }
})

module.exports = router

is it possible to send user_id through in res.redirect('profile.html') like res.redirect('profile.html', req.id)? I added my login.js code above

Bayram
  • 73
  • 11

1 Answers1

1

You can send it using URL query.

res.redirect(`login.html?user_id=${user_id}`);

The alternative solution is to store it in session before redirect and get it back from session storage in the next page.

req.session.user_id = user_id;
res.redirect('profile.html');

In profile.html you can access it like:

// From URL query
const userId = req.query.user_id;
// From session
const userId = req.session.user_id;
Masood
  • 1,545
  • 1
  • 19
  • 30