|
1 | 1 | #!/usr/bin/env node |
2 | 2 |
|
3 | 3 | const express = require('express') |
4 | | -const app = express() |
5 | | -const port = 3000 |
6 | 4 |
|
| 5 | +const app = express() |
7 | 6 | app.get('/', (req, res) => { |
8 | | - res.send('Hello World!') |
| 7 | + res.send('hello world') |
| 8 | +}) |
| 9 | +app.get('/error', async (req, res, next) => { |
| 10 | + try { |
| 11 | + throw 'my error' |
| 12 | + res.send('never returned') |
| 13 | + } catch(error) { |
| 14 | + next(error); |
| 15 | + } |
9 | 16 | }) |
| 17 | +const server = app.listen(3000, () => { |
| 18 | + console.log(`listening: http://localhost:${server.address().port}`) |
10 | 19 |
|
11 | | -app.listen(port, () => { |
12 | | - console.log(`Example app listening at http://localhost:${port}`) |
| 20 | + // Test it. |
| 21 | + function test(path, method, status, body) { |
| 22 | + const assert = require('assert') |
| 23 | + const http = require('http') |
| 24 | + const options = { |
| 25 | + hostname: 'localhost', |
| 26 | + port: server.address().port, |
| 27 | + path: path, |
| 28 | + method: method, |
| 29 | + } |
| 30 | + http.request(options, res => { |
| 31 | + console.error(res.statusCode); |
| 32 | + assert(res.statusCode === status); |
| 33 | + res.on('data', d => { |
| 34 | + if (body !== undefined) { |
| 35 | + assert(d.toString() === body); |
| 36 | + } |
| 37 | + }) |
| 38 | + }).end() |
| 39 | + } |
| 40 | + test('/', 'GET', 200, 'hello world') |
| 41 | + test('/', 'POST', 404) |
| 42 | + test('/dontexist', 'GET', 404) |
| 43 | + // Shows 'my error' on terminal, without stack trace. |
| 44 | + test('/error', 'GET', 500) |
13 | 45 | }) |
0 commit comments