I'm having an issue getting my backend to work.... honestly it's not even loading, I get the log that the server has started but entering in http://localhost:5000/api/items loads indefinitely. I'm not sure what I'm doing wrong.
This is my server.js
const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./items-routes');
const server = express();
server.use(bodyParser.json);
server.use('/api/items', routes);
const port = 5000;
try {
server.listen(port);
console.log(`Listening on port ${port}`);
} catch (error) {
console.log(error.message);
}
Here is my items-routes.js
const express = require('express');
const itemsController = require('./items-controller');
const router = express.Router();
router.get('/', itemsController.getItems);
router.post('/:iid', itemsController.createItem);
module.exports = router;
And finally my items-controller.js
const Item = require('./items-schema');
const items = [
{
title: 'This is a title',
description: 'This is a description',
},
{
title: 'This is another title',
description: 'This is another description',
},
{
title: 'This is a third title',
description: 'This is a third description',
},
];
const getItems = async (req, res, next) => {
res.json({
items: items.map((item) => {
item.toObject({ getters: true });
}),
});
console.log('These are the ITEMS!');
};
const createItem = async (req, res, next) => {
const { title, description } = req.body;
const createdItem = new Item({
title,
description,
});
try {
items.push(createItem);
console.log('You are posting an ITEM!');
} catch (error) {
return next(error);
}
res.status(201).json({ item: createdItem });
};
exports.getItems = getItems;
exports.createItem = createItem;
I initially had mongoose set-up to create a proper backend but now have dummy items in order to solve this issue before moving on. The server never worked but I have a similar project that did work.
I have a suspicion that I'm not understanding router.use/get/post properly but I've tried reading the documentation and only get more confused.