Merge pull request #480 from chentsulin/ctx.origin

implement ctx.origin
This commit is contained in:
Yiyu He 2015-09-21 22:23:44 +08:00
commit b3d46bd69e
3 changed files with 37 additions and 1 deletions

View file

@ -176,6 +176,7 @@ delegate(proto, 'request')
.access('query') .access('query')
.access('path') .access('path')
.access('url') .access('url')
.getter('origin')
.getter('href') .getter('href')
.getter('subdomains') .getter('subdomains')
.getter('protocol') .getter('protocol')

View file

@ -59,6 +59,17 @@ module.exports = {
this.req.url = val; this.req.url = val;
}, },
/**
* Get origin of URL.
*
* @return {String}
* @api public
*/
get origin() {
return this.protocol + '://' + this.host;
},
/** /**
* Get full request URL. * Get full request URL.
* *
@ -71,7 +82,7 @@ module.exports = {
if (/^https?:\/\//i.test(this.originalUrl)) { if (/^https?:\/\//i.test(this.originalUrl)) {
return this.originalUrl; return this.originalUrl;
} }
return this.protocol + '://' + this.host + this.originalUrl; return this.origin + this.originalUrl;
}, },
/** /**

24
test/request/origin.js Normal file
View file

@ -0,0 +1,24 @@
var Stream = require('stream');
var http = require('http');
var koa = require('../../');
var context = require('../context');
describe('ctx.origin', function(){
it('should return the origin of url', function(){
var socket = new Stream.Duplex();
var req = {
url: '/users/1?next=/dashboard',
headers: {
host: 'localhost'
},
socket: socket,
__proto__: Stream.Readable.prototype
};
var ctx = context(req);
ctx.origin.should.equal('http://localhost');
// change it also work
ctx.url = '/foo/users/1?next=/dashboard';
ctx.origin.should.equal('http://localhost');
})
})