chntgomez chntgomez - 1 month ago 10
Node.js Question

Render JSON as response in NodeJS

I have been using NodeJS to create a REST API service. I don't need to render any webpages or 'ejs' files.

With that In mind I need to know if there is an arquitecture to save JSON templates like the 'views' folder for storing '.ejs' templates to use them as response for let's say a profile.

Also, I have been working with passport module to authenticate users and I cannot pass the flash message to a JSON response, so far this is how it looks:

passport.use('local.signup', new LocalStrategy({
usernameFiled : 'email',
passwordField : 'password',
passReqToCallback : true
}, function(req, res, password, done){
User.findOne({'email' : email}, function(err, user){
if (err)
return done(err);
if (user)
return done(null, false, {message : 'Email already in use'});
var newUser = new User();
newUser.email = email;
newUser.password = newUser.encryptPassword(password);
newUser.save(function(err, result){
if (err)
return done(err);
return done(null, newUser);
});
});

})) ;


And this is my routing :

app.post('/signup', passport.authenticate('local.signup', {
successRedirect : '/me',
failureRedirect : '/loginerr',
failerFlash : true
}));

/*===== SECURE ==== */

app.get('/me', function(req, res, next){
res.end('Welcome user');
});

/* ========== Errors ====================== */

app.get('/loginerr', function(req, res, next){
var message = req.flash('error');
res.setHeader('Content-Type', 'application/json');
res.json({'error' : 'email already taken'}); //Here i should use the flash message instead.
});


As you can see, if there is an error when the user signs up, it is redirected to a /loginerr get, Instead of that i want to respond with a template of a JSON to respond with the flash message.

How can I do such thing?

Answer

Maybe you can need use JSON.stringify()

for example

app.get('/loginerr', function(req, res, next){
    res.setHeader('Content-Type', 'application/json');
    res.end(`{error:${req.flash('error')}}`)
});

Good Luck