From 89b7c02b4ae7fb6797767292870f99a6320e018d Mon Sep 17 00:00:00 2001 From: Adam Pancutt Date: Mon, 2 Nov 2020 14:51:55 +0100 Subject: [PATCH] Allow router.redirect() to accept external destinations (#110) * Allow router.redirect() to accept external destinations * Remove redundant case-insensitive flag * Added tests for router.redirect() with external destinations * Simplify external destination detection --- lib/router.js | 2 +- test/lib/router.js | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/router.js b/lib/router.js index 4c27578..a7f0871 100644 --- a/lib/router.js +++ b/lib/router.js @@ -532,7 +532,7 @@ Router.prototype.redirect = function (source, destination, code) { if (source[0] !== '/') source = this.url(source); // lookup destination route by name - if (destination[0] !== '/') destination = this.url(destination); + if (destination[0] !== '/' && !destination.includes('://')) destination = this.url(destination); return this.all(source, ctx => { ctx.redirect(destination); diff --git a/test/lib/router.js b/test/lib/router.js index 71c601a..1344f52 100644 --- a/test/lib/router.js +++ b/test/lib/router.js @@ -1305,6 +1305,36 @@ describe('Router', function () { done(); }); }); + + it('redirects to external sites', function (done) { + const app = new Koa(); + const router = new Router(); + app.use(router.routes()); + router.redirect('/', 'https://www.example.com'); + request(http.createServer(app.callback())) + .post('/') + .expect(301) + .end(function (err, res) { + if (err) return done(err); + res.header.should.have.property('location', 'https://www.example.com'); + done(); + }); + }); + + it('redirects to any external protocol', function (done) { + const app = new Koa(); + const router = new Router(); + app.use(router.routes()); + router.redirect('/', 'my-custom-app-protocol://www.example.com/foo'); + request(http.createServer(app.callback())) + .post('/') + .expect(301) + .end(function (err, res) { + if (err) return done(err); + res.header.should.have.property('location', 'my-custom-app-protocol://www.example.com/foo'); + done(); + }); + }); }); describe('Router#route()', function () {