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

Send 404s for assets and api calls that don't exist. #2

Open
wants to merge 1 commit into
base: starter
Choose a base branch
from
Open
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
30 changes: 24 additions & 6 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,30 @@ import express from 'express';
import bodyParser from 'body-parser';

const app = express();
const staticRouter = express.Router();
const apiRouter = express.Router();

const COMMENTS_FILE = path.join(__dirname, 'comments.json');
const INDEX = fs.readFileSync(path.join(__dirname, 'public', 'index.html'), {encoding: 'utf8'});
app.set('port', (process.env.PORT || 4000));

app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
const notFound = (req, res, next) => {
res.status(404).send(`${req.originalUrl} Not Found.`);
};

const errorHandler = (err, req, res, next) => {
res.status(500).send('Server error');
};

staticRouter.use('/', express.static(path.join(__dirname, 'public')));
staticRouter.use(/^\/(css|scripts)/, notFound);

apiRouter.use(bodyParser.json());
apiRouter.use(bodyParser.urlencoded({
extended: true
}));

app.get('/api/comments', (req, res) =>
apiRouter.get('/comments', (req, res) =>
fs.readFile(COMMENTS_FILE, (err, data) => {
if (err) {
console.error(err);
Expand All @@ -38,7 +50,7 @@ app.get('/api/comments', (req, res) =>
})
);

app.post('/api/comments', (req, res) =>
apiRouter.post('/comments', (req, res) =>
fs.readFile(COMMENTS_FILE, (err, data) => {
if (err) {
console.error(err);
Expand All @@ -65,7 +77,7 @@ app.post('/api/comments', (req, res) =>
})
);

app.get('/api/authors/:author', (req, res) => {
apiRouter.get('/authors/:author', (req, res) => {
console.log('author: ', req.params.author);
fs.readFile(COMMENTS_FILE, (err, data) => {
if (err) {
Expand All @@ -79,10 +91,16 @@ app.get('/api/authors/:author', (req, res) => {
});
});

apiRouter.use(notFound);

app.use('/', staticRouter);
app.use('/api', apiRouter);

app.use('/', (req, res) => {
res.send(INDEX)
});

app.use('/', errorHandler);


app.listen(app.get('port'), function() {
Expand Down