신동해

Update server.js : add filtering function of lib/pro news, make api-request dynamic

Showing 1 changed file with 98 additions and 47 deletions
...@@ -3,65 +3,116 @@ const app = express(); ...@@ -3,65 +3,116 @@ const app = express();
3 const bodyParser = require('body-parser') 3 const bodyParser = require('body-parser')
4 app.use(bodyParser.urlencoded({extended : true})); 4 app.use(bodyParser.urlencoded({extended : true}));
5 app.set('view engine', 'ejs'); 5 app.set('view engine', 'ejs');
6 +app.use('/public', express.static('public'));
7 +const fs = require('fs'); // JSON 파일 읽기
6 8
9 +// 네이버 검색 Open API 예제 - 블로그 검색
10 +var client_id = 'Q5XjQPuQgvUh7MQCyBHx';
11 +var client_secret = 'dF9OQ6AqrV';
12 +
13 +// DB 연결
7 var db; 14 var db;
8 const MongoClient = require('mongodb').MongoClient; 15 const MongoClient = require('mongodb').MongoClient;
9 -MongoClient.connect('mongodb+srv://admin:qwer1234@cluster0.m2pvs.mongodb.net/myFirstDatabase?retryWrites=true&w=majority', function(에러, clinet){ 16 +MongoClient.connect('mongodb+srv://admin:qwer1234@cluster0.m2pvs.mongodb.net/myFirstDatabase?retryWrites=true&w=majority', function(에러, client){
10 - // 연결되면 할 17 + // 연결되면 할
11 if(에러){ 18 if(에러){
12 return console.log(에러); 19 return console.log(에러);
13 } 20 }
14 - db = clinet.db('todoapp'); 21 + else{
15 - 22 + db = client.db('OPPOV');
16 - app.listen(8080, function(){
17 - console.log('listening on 8080')
18 - });
19 -
20 -});
21 23
22 -app.get('/pet', function(요청, 응답){ 24 + app.listen(8080, function(){
23 - 응답.send('펫쇼핑할 수 있는 페이지입니다.'); 25 + console.log('listening on 8080')
24 -}); 26 + });
25 - 27 + }
26 -app.get('/beauty', function(요청, 응답){
27 - 응답.send('뷰티용품 쇼핑할 수 있는 페이지입니다.');
28 }); 28 });
29 29
30 +// 메인 페이지
30 app.get('/', function(요청, 응답){ 31 app.get('/', function(요청, 응답){
31 - 응답.sendFile(__dirname + '/index.html'); 32 + 응답.render('index.ejs');
32 -}); 33 +})
33 34
34 -app.get('/write', function(요청, 응답){ 35 +// 진보,보수 동시 검색 페이지
35 - 응답.sendFile(__dirname + '/write.html'); 36 +app.get('/list',function(요청, 응답){
37 + 응답.render('list.ejs', {주제 : 요청.query.subject});
36 }); 38 });
37 39
38 -app.post('/add', function(요청, 응답){ 40 +// 보수 측 네이버 뉴스 검색
39 - 응답.send('전송완료'); 41 +app.get('/result/liberal/:subject', function (req, res) {
40 - db.collection('counter').findOne({name : '게시물갯수'}, function(에러, 결과){ 42 + var api_url = 'https://openapi.naver.com/v1/search/news.json?query=' + encodeURI(req.query.query); // json 결과
41 - console.log(결과.totalPost) 43 + // var api_url = 'https://openapi.naver.com/v1/search/blog.xml?query=' + encodeURI(req.query.query); // xml 결과
42 - var 총게시물갯수 = 결과.totalPost 44 + var request = require('request');
43 - 45 + const option = {
44 - db.collection('post').insertOne({ _id : 총게시물갯수 + 1, 제목 : 요청.body.title, 날짜 : 요청.body.date}, function(에러, 결과){ 46 + query : req.params.subject,
45 - console.log('저장완료') 47 + start :1,
46 - // counter라는 콜렉션에 있는 totalPost라는 항목도 1 증가시켜야함 48 + display :100,
47 - db.collection('counter').updateOne({name:'게시물갯수'},{ $inc : {totalPost:1} },function(){ 49 + sort :'sim'
48 - if(에러){ 50 + }
49 - return console.log(에러) 51 + var options = {
50 - } 52 + url: api_url,
51 - }) 53 + qs : option,
52 - }); 54 + headers: {'X-Naver-Client-Id':client_id, 'X-Naver-Client-Secret': client_secret}
55 + };
56 + request.get(options, function (error, response, body) {
57 + if (!error && response.statusCode == 200) {
58 + const jsonData = JSON.parse(body);
59 + const result = jsonData;
60 + // 보수 뉴스만 걸러내기
61 + var i;
62 + var news = [];
63 + for (i=0; i<parseInt(result.display); i++){
64 + var con = result.items[i].originallink.includes('chosun') | result.items[i].originallink.includes('joongang') | result.items[i].originallink.includes('donga')
65 + if (con){
66 + news.push(result.items[i])
67 + }
68 + else{
69 + continue;
70 + }
71 + }
72 + res.render('result_lib.ejs', {posts : news, num : news.length})
73 + } else {
74 + res.status(response.statusCode).end();
75 + console.log('error = ' + response.statusCode);
76 + }
53 }); 77 });
54 -}); 78 + })
55 79
56 -app.get('/list',function(요청, 응답){
57 - // DB에 저장된 post라는 collectino안의 ~~인 데이터를 꺼내주세요
58 - db.collection('post').find().toArray(function(에러, 결과){
59 - console.log(결과);
60 - 응답.render('list.ejs', {posts : 결과});
61 - })
62 -});
63 -
64 -app.delete('/delete',function(요청,응답){
65 - console.log(요청.body)
66 -
67 -})
...\ No newline at end of file ...\ No newline at end of file
80 +// 진보 측 네이버 뉴스 검색
81 +app.get('/result/progress/:subject', function (req, res) {
82 + var api_url = 'https://openapi.naver.com/v1/search/news.json?query=' + encodeURI(req.query.query); // json 결과
83 + // var api_url = 'https://openapi.naver.com/v1/search/blog.xml?query=' + encodeURI(req.query.query); // xml 결과
84 + var request = require('request');
85 + const option = {
86 + query : req.params.subject,
87 + start :1,
88 + display :100,
89 + sort :'sim'
90 + }
91 + var options = {
92 + url: api_url,
93 + qs : option,
94 + headers: {'X-Naver-Client-Id':client_id, 'X-Naver-Client-Secret': client_secret}
95 + };
96 + request.get(options, function (error, response, body) {
97 + if (!error && response.statusCode == 200) {
98 + const jsonData = JSON.parse(body);
99 + const result = jsonData;
100 + // 진보뉴스만 걸러내기
101 + var i;
102 + var news = [];
103 + for (i=0; i<parseInt(result.display); i++){
104 + var con = result.items[i].originallink.includes('hani') | result.items[i].originallink.includes('khan') | result.items[i].originallink.includes('ohmynews')
105 + if (con){
106 + news.push(result.items[i])
107 + }
108 + else{
109 + continue;
110 + }
111 + }
112 + res.render('result_pro.ejs', {posts : news, num : news.length})
113 + } else {
114 + res.status(response.statusCode).end();
115 + console.log('error = ' + response.statusCode);
116 + }
117 + });
118 + });
...\ No newline at end of file ...\ No newline at end of file
......