-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
60 lines (53 loc) · 1.58 KB
/
app.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
// 模块引用
const express = require('express');
const cheerio = require('cheerio');
const url = require('url');
const bodyParser = require('body-parser');
const tool = require('./public/tool');
const port = process.env.PORT || '3000';
const app = express();
// 打印日志
app.use((req, res, next) => {
const method = req.method;
const requestUrl = req.originalUrl;
const router = url.parse(requestUrl);
const date = new Date();
const currentTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.toLocaleTimeString();
console.log(`${method} ${router.path} ${currentTime}`);
next();
});
// 首页发送数据
app.get('/', (req, res) => {
res.send(`hello expresss`);
});
// 爬虫测试
app.get('/get_cnode_info', (req, res) => {
const url = 'https://cnodejs.org/';
tool.requestPromise('get', url)
.then(reply => {
const $ = cheerio.load(reply);
let items = [];
$('#topic_list .topic_title').each(function (index, element) {
const $element = $(element);
items.push({
title: $element.attr('title'),
href: $element.attr('href')
});
});
$('#topic_list .user_avatar').each(function (index, element) {
const $element = $(element);
const img = $element.children('img');
items[index].author = img.attr('title');
});
res.json(items);
})
.catch(err => {
console.log(err);
res.status(500);
res.json(err.message);
})
});
// 服务端开启
app.listen(port, () => {
console.log(`server start on ${port}`);
});