My backend is not functioning properly. The server is starting without any issues, but when I try to access http://localhost:5000/api/items, it just loads indefinitely. I am unsure of what I am doing wrong.
Below is my server.js file:
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 file:
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 my items-controller.js file:
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 for the backend, but I replaced it with dummy items to troubleshoot the issue. I have successfully set up a similar project before, so this is confusing to me.
I suspect that my understanding of router.use/get/post might be incorrect, despite my attempts to read the documentation. I feel more confused than before.