Workkkkk
Workkkkk

Reputation: 285

ExpressJS: How to send data to URL

I have a post request which redirects to a new route as you can see

 //POST login 
 app.post('/login', urlencodedParser, function(req,res){
    userLogin(req.body, function(response){
        if(response == true){
            //Activate player login in db
            loginPlayerDB(req.body.username);
            getPlayerId(req.body.username, function(id){
                res.redirect(req.baseUrl + '/:id/profile');
            });
        } else{
            res.send(500, "Username or Password is incorrect");
        }
    })
});

This function gets called

 function getPlayerId(username, callback){
    let sql = "SELECT PlayerId FROM users WHERE Username = (?)";
    var values = [username];
    db.query(sql, values, function(err, result, fields){
        if(err){
            console.log(err);
        } else{
               return callback(result);
        }
    })
}

It redirects to this route

app.get('/:id/profile', function(req,res){
    res.render('profile/profile');
})

Everything works great except the URL on the new page is

http://localhost:3000/:id/profile

When it should be something like

http://localhost:3000/6/profile

If the player has an id of 6. How do I fix this

//Solution.

Thank you to MadWard for the help. My mistake was that in my getPlayerId function, I return result, which is an array, instead of result[0].PlayerId in order to get the specific id I was looking for

Upvotes: 0

Views: 115

Answers (1)

Azami
Azami

Reputation: 2171

You are literally redirecting to /:id/profile. This is a string, it is fixed, and will always be '/:id/profile'.

What you want to do instead is, using template strings:

        getPlayerId(req.body.username, function(id){
            res.redirect(`${req.baseUrl}/${id}/profile`);
        });

Using normal string concatenating like you were doing:

        getPlayerId(req.body.username, function(id){
            res.redirect(req.baseUrl + '/' + id + '/profile');
        });

Upvotes: 1

Related Questions