Redirecting a Response

When you’re implementing a webserver, you may need to redirect a request from the client to a different location on the same server or on a completely different server. The res.redirect(path) method handles redirection of a request to a new location.

Listing 18.7 illustrates the various redirection addressing that you can use. Line 6 redirects to a completely new domain address. Line 9 redirects to a different path on the same server, and line 15 redirects to a relative path on the same server.

Listing 18.7 express_redirect.js: Redirecting requests on an Express server


01 var express = require('express'),
02 var url = require('url'),
03 var app = express();
04 app.listen(80);
05 app.get('/google', function (req, res) {
06   res.redirect('http://google.com'),
07 });
08 app.get('/first', function (req, res) {
09   res.redirect('/second'),
10 });
11 app.get('/second', function (req, res) {
12   res.send("Response from Second");
13 });
14 app.get('/level/A', function (req, res) {
15   res.redirect("/level/B");
16 });
17 app.get('/level/B', function (req, res) {
18   res.send("Response from Level B");
19 });


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.251.163