Rob McCormack Rob McCormack - 3 months ago 17
Node.js Question

Can't access customData in view for non-logged in user - Express.js Stormpath

Following this tutorial:


https://stormpath.com/blog/build-nodejs-express-stormpath-app


I can easily access and display in view profile.jade, customData for logged in user , from profile.js with

username: req.user.username,
city: req.user.customData.city,


Filename: profile.jade

h1 This is surname #{username} and #{city}





I want to display in a view, data for a non-logged in user at URL:
http://localhost:3000/-jsmith
which I got working - except I can't access any customData.

FILENAME: server.js
I do have this set.

app.use(stormpath.init(app, {
expand: {
customData: true


and

app.get('/-:id', function(req, res, next) {
console.log('the response will be sent by the next function ...');
var id = req.params.id;
next();
},
function(req, res) {
var id = req.params.id;
req.app.get('stormpathApplication').getAccounts({
username: id

}, (err, accounts) => {
if (err) throw err;
accounts.each((account, cb) => {
console.log('Found matching account:', account);
cb();
res.render('user', {
email: account.email,
city: account.customData.city,

});

});
});
}
);


The problem:



Filename: user.jade

username is displayed, but nothing for city

h1 This is surname #{username} and #{city}


Where am I going wrong?

Answer

If you're taking the Stormpath Application object directly and making API calls with it, you'll actually need to add the { expand: 'customData' } parameter to each API call.

I know you've set it for your express-stormpath configuration already -- this only applies to API calls the application makes on your behalf (for instance the req.user). I can see how this may seem confusing.

So to make this work, simply replace:

    req.app.get('stormpathApplication').getAccounts({
        username: id
    }

With:

    req.app.get('stormpathApplication').getAccounts({
        username: id,
        expand: 'customData'
    }

And things should work. Happy coding!

Comments