stackdisplay
stackdisplay

Reputation: 2045

Cannot redirect when doing post request

I am using request module for doing post request. After the post request, I wish to redirect user. But it seems to me that i am unable to do redirect here.

function callApi(req, res) {
    request(options, function(err, response, body){
        res.redirect('/'); //cannot read property redirect of undefined, can't set headers after they are sent
    });
}

function callApi(req, res) {
    request(options, function(err, response, body){
        req.res.redirect('/'); // can't set headers after they are sent
    });
}

Upvotes: 0

Views: 112

Answers (1)

Deendayal Garg
Deendayal Garg

Reputation: 5148

Inside callback your res would refer the response from request callback. do this...

function callApi(request, response) {
request(options, function(req, res, body){
    response.redirect('/'); //cannot read property redirect of undefined, can't set headers after they are sent
   });
}

function callApi(request, response) {
   request(options, function(req, res, body){
      response.redirect('/'); // can't set headers after they are sent
   });
}

Upvotes: 1

Related Questions