From 9dbd2da813ac65aafbc8916735f5674252d70879 Mon Sep 17 00:00:00 2001 From: William Lumanauw Date: Sat, 29 Aug 2020 17:24:13 +0800 Subject: [PATCH] submit quiz chapter 5 --- middlewares.js | 13 ++++++++++++- routes.js | 18 +++++++++++++++++- server.js | 13 +++++++++++++ 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/middlewares.js b/middlewares.js index 0a225b7..2a79a02 100644 --- a/middlewares.js +++ b/middlewares.js @@ -1,3 +1,4 @@ + const logger = (req, res, next) => { let d = new Date(); let timestamp = d.toJSON().slice(0,19).replace('T',':'); @@ -7,6 +8,16 @@ const logger = (req, res, next) => { const notFoundHandler = (req, res, next) => { res.status(404).send("URL not found"); + next(); +} + +const intServerError = (err, req, res, next) => { + console.error(err) + res.status(500).json({ + status: 'internal error', + errors: err.message + }) + next(); } -module.exports = {logger, notFoundHandler}; \ No newline at end of file +module.exports = {logger, notFoundHandler, intServerError}; \ No newline at end of file diff --git a/routes.js b/routes.js index cf2762e..10134f1 100644 --- a/routes.js +++ b/routes.js @@ -1,7 +1,7 @@ const express = require('express'); const newsApi = require('newsapi'); -const news = new newsApi('YOUR_API_HERE'); +const news = new newsApi('656c0b1056d84d6ca448684dee0120fd'); const router = express.Router(); // basic routing router.get('/news', (req, res) => { @@ -20,4 +20,20 @@ router.get('/news', (req, res) => { }); }) +router.get('/sports', (req, res) => { + news.v2.everything({ + q: req.query.q, + q:'sports', + }).then(result => { + if(result.status === "ok") { + let articles = result.articles; + res.render('news', { + articles + }) + } else { + res.send('Cannot fetch news.') + } + }); +}) + module.exports = router; \ No newline at end of file diff --git a/server.js b/server.js index ff4a8cf..3b7d554 100644 --- a/server.js +++ b/server.js @@ -1,11 +1,24 @@ const express = require('express'); const router = require('./routes'); +// const logger = require('./middlewares'); +const {notFoundHandler, logger, intServerError}= require('./middlewares'); + +const path = require('path'); + // inisialisasi app const app = express(); const port = process.env.PORT || 5000; app.set('view engine', 'ejs'); + +app.use(logger); +app.use('*/css', express.static(path.join(__dirname, 'public/css'))) + app.use(router); +app.use(intServerError); +app.use(notFoundHandler); + +// app.get(notFoundHandler); // Body parser, reading data from body into req.body app.use(express.json());