forked from senchalabs/connect
/
server.js
92 lines (77 loc) · 2.18 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
var connect = require('../');
describe('app', function(){
it('should inherit from event emitter', function(done){
var app = connect();
app.on('foo', done);
app.emit('foo');
})
it('should not obscure FQDNs', function(done){
var app = connect();
app.use(function(req, res){
res.end(req.url);
});
app.request()
.get('http://example.com/foo')
.expect('http://example.com/foo', done);
})
it('should allow old-style constructor middleware', function(done){
var app = connect(
connect.json()
, connect.multipart()
, connect.urlencoded()
, function(req, res){ res.end(JSON.stringify(req.body)) });
app.stack.should.have.length(4);
app.request()
.post('/')
.set('Content-Type', 'application/json')
.write('{"foo":"bar"}')
.expect('{"foo":"bar"}', done);
})
it('should allow old-style .createServer()', function(){
var app = connect.createServer(
connect.json()
, connect.multipart()
, connect.urlencoded());
app.stack.should.have.length(3);
})
it('should work as middlware', function(done){
var http = require('http');
// custom server handler array
var handlers = [connect(), function(req, res, next){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Ok');
}];
// execute callbacks in sequence
var n = 0;
function run(req, res){
if (handlers[n]) {
handlers[n++](req, res, function(){
run(req, res);
});
}
}
// create a non-connect server
var server = http.createServer(run).listen(5556, function(){
http.get({
host: 'localhost',
port: 5556,
path: '/'
}, function(res){
var buf = '';
res.setEncoding('utf8');
res.on('data', function(s){ buf += s });
res.on('end', function(){
buf.should.eql('Ok');
server.close();
done();
});
});
});
})
it('should escape the 404 response body', function(done){
var app = connect();
app.request()
.get('/foo/<script>stuff</script>')
.expect('Cannot GET /foo/<script>stuff</script>', done);
})
})