Code Snippet - How to Handler Redirect within Node.js

2014/5/21 min read
bookmark this
Responsive image

at node.js server side, you want to redirect to another url after you success get response from one api.

you can try use request module.


exports.server_side_api = function(req, res) {
        var options = {
            url: 'http://localhost:100/api/firstAPI/',
            headers: {
                'Content-Type': 'application/json'
            }
        };
      
          request(options, function (error, response, body) {
                  if (!error && response.statusCode == 200) {
                    
                    var info = JSON.parse(body);
                    // redirect to another url.
                    res.statusCode = 302; 
                    res.setHeader("Location", info.Url);
                    res.end();
                  }
              });
}


When use node.js module, you have to save it to package.json file, so when you deploy or use at other enviroment by running following, system will install the all the dependency module from your package.json file.

npm install

You can run following code it will instll the module and update the package.json

npm install request --save

npm-install document