ctx.request.href: get full request url, include protocol, host and originalUrl

Useful on those scenes need current full request url, like `OAuth`.
This commit is contained in:
fengmk2 2014-11-23 16:00:17 +08:00 committed by Jonathan Ong
parent d58f458b8d
commit 3e66157472
5 changed files with 74 additions and 0 deletions

View file

@ -148,6 +148,7 @@ koa uses [http-assert](https://github.com/jshttp/http-assert) for assertions.
- `ctx.url`
- `ctx.url=`
- `ctx.originalUrl`
- `ctx.href`
- `ctx.path`
- `ctx.path=`
- `ctx.query`

View file

@ -39,6 +39,15 @@
Get request original URL.
### request.href
Get full request URL, include `protocol`, `host` and `url`.
```js
this.request.href
// => http://example.com/foo/bar?q=1
```
### request.path
Get request pathname.

View file

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

View file

@ -59,6 +59,21 @@ module.exports = {
this.req.url = val;
},
/**
* Get full request URL.
*
* @return {String}
* @api public
*/
get href() {
// support: `GET http://example.com/foo`
if (/^https?:\/\//i.test(this.originalUrl)) {
return this.originalUrl;
}
return this.protocol + '://' + this.host + this.originalUrl;
},
/**
* Get request method.
*

48
test/request/href.js Normal file
View file

@ -0,0 +1,48 @@
var Stream = require('stream');
var http = require('http');
var koa = require('../../');
var context = require('../context');
describe('ctx.href', function(){
it('should return the full request 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.href.should.equal('http://localhost/users/1?next=/dashboard');
// change it also work
ctx.url = '/foo/users/1?next=/dashboard';
ctx.href.should.equal('http://localhost/users/1?next=/dashboard');
})
it('should work with `GET http://example.com/foo`', function(done){
var app = koa()
app.use(function* (){
this.body = this.href
})
app.listen(function(){
var address = this.address()
http.get({
host: 'localhost',
path: 'http://example.com/foo',
port: address.port
}, function(res){
res.statusCode.should.equal(200)
var buf = ''
res.setEncoding('utf8')
res.on('data', function(s){ buf += s })
res.on('end', function(){
buf.should.equal('http://example.com/foo')
done()
})
})
})
})
})