-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (53 loc) · 1.45 KB
/
index.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 bodyParser = require('body-parser');
const app = express();
const Article = require('./db').Article; //加载数据库模块
const read = require('node-readability');
app.set('port', process.env.PORT || 3000);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/articles', (req, res, next) => {
Article.all((err, articles) => {
if (err) return next(err);
// res.send(articles);
res.format({
html: () => {
res.render('articles.ejs', { articles });
},
json: () => {
res.send(articles);
}
});
})
});
app.get('/articles/:id', (req, res, next) => {
const id = req.params.id;
Article.find(id, (err, article) => {
if (err) return next(err);
res.send(article);
})
});
app.delete('/articles/:id', (req, res, next) => {
const id = req.params.id;
Article.delete(id, (err) => {
if (err) return next(err);
res.send({ message: 'Deleted' });
})
});
app.post('/articles', (req, res, next) => {
const url = req.body.url;
read(url, (err, result) => {
if (err || !result) res.status(500).send('Error downloading article');
Article.create(
{ title: result.title, content: result.content },
(err, article) => {
if (err) return next(err);
res.send('ok');
}
)
})
})
app.listen(app.get('port'), () => {
console.log('App started on port', app.get('port'))
})
module.exports = app;