Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

submit quiz chapter 5 #8

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion middlewares.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

const logger = (req, res, next) => {
let d = new Date();
let timestamp = d.toJSON().slice(0,19).replace('T',':');
Expand All @@ -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};
module.exports = {logger, notFoundHandler, intServerError};
18 changes: 17 additions & 1 deletion routes.js
Original file line number Diff line number Diff line change
@@ -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) => {
Expand All @@ -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;
13 changes: 13 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -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());
Expand Down