简体   繁体   中英

How to pass variables from Jade to Node.js endpoint function

I'm new to express and I want to pass the user.username from a jade file to the endpoint function in my javascript file. This is the endpoint function in index.js:

router.get('/userdetail', function(req, res) {

   console.log(req.params)
   console.log(req.body)

   res.render('userdetail', { title: 'User Detail' });
});

This is my jade file:

extends layout
block content
    h1.
        User List
    ul
        each user, i in userlist
        li
            a(href="/userdetail/#{user.username}")= user.username

Basically, I'd like for the link to point to the user's page without needing to manually hardcode each user. If there's some way to do this in angularjs that would be fine too.

EDIT: I edited my code as below but console.log() gave me undefined.

index.js:

router.get('/userdetail', function(req, res) {

   console.log(req.query.username);

   res.render('userdetail', { title: 'User Detail' });
});

userdetail.jade:

extends layout
block content
    h1.
        User List
    ul
        each user, i in userlist
            li
                a(href="mailto:#{user.email}")= user.username    
                a(href="/userdetail/?username = {user.username}")= user.username

You could set the username as a query parameter

a(href="/userdetail/?username={user.username}")= user.username

And access it in request.query ie request.query.username

Please note I might not have the correct jade syntax

You need to pass the user object as an options argument to the res.render command. Maybe something like this:

router.get('/userdetail', function(req, res) {

  locals = req.body.userlist

  res.render('userdetail', locals);

});

You just need to figure out how to retrieve the userlist from the request object and then pass it into the render options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM