Home > other >  Express Router: I'm having an issue getting my routes to work, the page doesn't load
Express Router: I'm having an issue getting my routes to work, the page doesn't load

Time:07-28

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.

CodePudding user response:

All of your code is actually 100% okay, you just applied the bodyParser.json middleware function incorrectly. The bodyParser.json function is not a middleware function itself, it is a function that takes an options object, then when it's called it returns a middleware function.

So, to fix your code, you just need to add () to call the function:

const express = require('express');
const bodyParser = require('body-parser');

const routes = require('./items-routes');

const server = express();

server.use(bodyParser.json()); // <- Call the bodyParser.json() function

server.use('/api/items', routes);

const port = 5000;

try {
  server.listen(port);
  console.log(`Listening on port ${port}`);
} catch (error) {
  console.log(error.message);
}

The reason it was hanging forever is because Express was waiting on the bodyParser.json function to call next() before moving forward; however, it never does that, so it just hangs.

Side note:

By the way, you don't need the body-parser module anymore if you're using the latest version of Express. Your code can be changed to this:

server.use(express.json());

And it'll work just the same just without the extra dependency.

  • Related