-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
46 lines (40 loc) · 1005 Bytes
/
index.js
File metadata and controls
46 lines (40 loc) · 1005 Bytes
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
var request = require('request');
var restify = require('restify');
const API_URL = 'http://api.laifudao.com/open/xiaohua.json';
var app = restify.createServer({
name: 'jokes'
});
app.get('/joke', (req, res) => {
request(API_URL, (err, response, body) => {
if (err) {
console.error(err);
return res.send({
type: 'Error',
data: [{
code: 102,
message: err.toString()
}]
});
}
if (response.statusCode === 200) {
body = body.trim().replace(/\s/g, '');
var jokes = JSON.parse(body);
var joke = jokes[Math.floor(Math.random() * jokes.length)];
return res.send({
type: 'Text',
data: [joke.content.trim().replace(/"/g, '\"').replace(/<br\/>/g, '')]
});
} else {
return res.send({
type: 'Error',
data: [{
code: 601,
message: body
}]
});
}
});
});
app.listen(3000, () => {
console.log('listening at 3000');
});