Code Snippet - How to Handle Redirect within Node.js
2014/05/022 min read
bookmark this
Table of Contents
Introduction
On the Node.js server side, if you want to redirect to another URL after successfully getting a response from an API, you can use the request module.
Redirect Example
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();
}
});
}
Installing the Request Module
When using a Node.js module, you have to save it to the package.json file. When you deploy or use it in another environment, running the following command will install all the dependency modules from your package.json file.
npm install
You can run the following command to install the module and update package.json:
npm install request --save
Conclusion
Redirecting within Node.js is straightforward — set the status code to 302 and the Location header to the target URL. Make sure to install and save the request module to your package.json so dependencies are properly managed across environments.