ton1
ton1

Reputation: 7628

Express.js res.render not redirecting, just displayed in console

This time I want to use res.render to display html as success of DB update. I did it several times, but this time it doesn't work. It's not render html file, just displayed on chrome's console.

I think it caused because of async problem or duplicated response. I tried to many ways but I couldn't solve it, so pointers appreciated.

The code is related when the user paid service, increase user's level.

Get Access Token => Validate => res.render

app.post('/payment/validate', function(req, res, next){

// Get access token 
request.post({
    url : 'https://payment-company/get/token'
}, function(err, response, body) {
    if(!err & response.statusCode == 200) {
        var result = JSON.parse(body);
        var accessToken = result.response.access_token;

    // Validate payment (compare paid and would be paid)
        request.get({
            headers : { 'Authorization' : accessToken }
            url : 'https://payment-company/find/paymentid'
        }, function (err, response, body) {

            if (!err && response.statusCode == 200){
                var result = JSON.parse(body);

                if (result.response.amount == req.body.price){
                    Members.findOne({id : req.user.id}, function(err, member){

                        // If no problem, update user level
                        member.level = 2;
                        member.save(function(err, result){
                            if (err) return next();

                            res.render('payment.view.result.ejs',
                                {
                                    title : 'Success !',
                                    description : 'level up.'
                                });
                        });
                    });
                } 
            } else {
                ...
            }
        }); 
    }
})
});

sorry to verbose code I tried to shorten code, No problem until res.render, res.render will work but it's not display page instead it just send html code to chrome's console.

Upvotes: 1

Views: 2357

Answers (1)

swider
swider

Reputation: 3444

Looks like there's a bit of a misunderstanding of how these requests work. What I think you intend:

  1. Browser makes a GET request, server responds with an HTML document, the browser renders it
  2. User takes an action
  3. Browser makes a POST request, server responds with an HTML document, the browser renders it

What you've started coded on the frontend is an alternate method:

  1. You make a POST request via AJAX, server responds with some JSON, you modify the current document with JavaScript to let the user know

Upvotes: 1

Related Questions