Having trouble with my routes in Express Router - the page just won't load!

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.

Answer №1

Your code is perfectly fine, you just need to correct how you are using the bodyParser.json middleware function. The bodyParser.json function is not a middleware function itself; instead, it is a function that takes an options object and returns a middleware function when called.

To resolve the issue, simply add () to properly call the function:

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

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

const server = express();

server.use(bodyParser.json()); // Correct way to call bodyParser.json()

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

const port = 5000;

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

The reason for the hanging issue was that Express was stuck waiting for the bodyParser.json function to call next() before proceeding, which never happened.

Additional information:

If you are using the latest version of Express, you can eliminate the need for the body-parser module by updating your code to this:

server.use(express.json());

This change will achieve the same functionality without the need for an extra dependency.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extract information from a string to retrieve the array specifications

After making a request to the server, I received the following response: { "statusCode": 200, "body": "{\"Errors\":\"\",\"Message\":\"\",\"Output\":\"\",\"TokenID\":\"F10645774 ...

remove a row from a table within a Firestore database

I'm currently working on implementing a button to delete a specific row in my table from the Firebase database, but I'm uncertain about how to achieve this using a button function. My code is written in JavaScript and utilizes Firestore. Below i ...

Tips for extracting information from an HTML table into a function using Google Apps Script

I am experiencing difficulties in coding this. I have attempted to use google.script.run but it's not working as expected. When I click the button "Approved," the data should be sent to a function, but I'm unsure of what steps to take next. I fee ...

What is the best way in jQuery to show each element of an array one at a time with a space in an input field?

I have a large array filled with strings that I want to display one by one in a text field, automatically concatenated with a space bar. Below is my code: <script> x = 0; function abc() { for (i = 0; i < words[x].length; i++) { ...

Binding Events to Elements within an AngularJS-powered User Interface using a LoopIterator

I am working with an Array of Objects in AngularJS that includes: EmployeeComments ManagerComments ParticipantsComments. [{ "id": "1", "title": "Question1", "ManagerComment": "This was a Job Wel Done", "EmployeeComment": "Wow I am Surprised", ...

Tips on maintaining the content of an element within a directive template

I'm currently facing an issue with adding the ng-click directive to a button. Here's my HTML: <button class="btn">clicky</button> This is the directive I am using: angular.module('app').directive('btn', function ...

Struggling to make comparisons with numerical data from MongoDB in an ExpressJS route

I am currently developing a website using Node.js, EJS template, MongoDB, and Express. I am working on implementing search functionality on my page using forms, but I am encountering a small issue. The problem is related to a logical issue in the search f ...

Struggling to make an AJAX form function properly

I'm running into an issue while setting up a basic AJAX form. My goal is to have a message display on the same page upon successful login using a PHP form through AJAX, but currently, I get redirected to the PHP file after form submission. Can anyone ...

Unable to reach the object property while using the $.each method

Upon receiving an object from an ajax request, I am using $.each to iterate through all the appointments in the object. However, I am encountering an issue where the object appears to be undefined within the $.each loop. Here is the code snippet for my req ...

The Angular method for retrieving the child's ID when it is clicked

As a newcomer to Angular 1.0 with a background in jQuery, I am facing the following scenario: Let's imagine we have the following HTML structure : <div id="filters"> <div id="filter1">Filter 1</div> <div id="filter2"> ...

Encountering a problem during the creation of a fresh Angular 2 project

After installing AngularJs with the command npm install -g angular-cli, I encountered an error when trying to create a new project: Cannot find module 'reflect-metadata' How can I resolve this error? ...

Express: simplifying the use of middleware for app implementation

I am looking to update the code in my index.js file app.use(require('sass-middleware').middleware({ src: path.resolve(__dirname, '../'), dest: path.resolve(__dirname, '../public') })); app.use(require('browserify-dev ...

What could be the reason behind the malfunctioning of a custom filter in this specific Vue 3 application?

In my development project, I am creating a Vue 3 CRUD application for managing Users. The goal is to display the users in reverse order so that the newest additions appear at the top. To achieve this, I have implemented a custom filter as shown below: reve ...

Unable to Add Dependency to Subclassed Object

In my setup, there are three classes that interact with each other. I am utilizing inversify for handling dependency injection. However, I encountered an issue when I injected the class MessageBroker into the derived class Repository and found that the Mes ...

What is the best method to place files from a file input into an array in the Firefox browser?

(I am using Vue 3) I have a functionality where I add files from an input file to an array, and then conditionally render these file names. Everything works perfectly on Chrome, but I encountered an issue with Mozilla Firefox. In Firefox, the array of file ...

Guide to configuring NPM Express to direct to index.html, bundle.js, and embedded css files

I've encountered an issue with my project setup. In my index.html file, I have paths pointing to my bundle.js and several CSS files located in nested directories (/css/ for my own files and /css/bootstrap/ for Bootstrap files). dirname/server.js dirn ...

Emphasize a passage by clicking on a different section of text

Seeking Assistance I am currently customizing this template which incorporates the MixItUp plugin. My query pertains to highlighting the "filter tab" upon clicking on the corresponding text when hovering over each image, a task I find challenging as a new ...

Is there a way to extract the content from a dynamic textbox using a dynamic button in HTML and AJAX?

My current task involves fetching data from a database and updating the records individually. I have created a table with a text input field and a button that will be generated dynamically for each record. The text input field is populated with the previou ...

What is the best way to show nested objects in JavaScript?

let paragraph = document.createElement('p'); document.body.appendChild(paragraph) const fruit = { type: 'Apple', properties: { color: 'Green', price: { bulk: '$3/kg', smallQty: '$4/kg' ...

Getting Started with Material UI's Default Components

After working with bootstrap, I decided to explore the material ui framework as well. However, when trying to use the default MUI component without customization, such as the card component, I encountered some difficulties. Here is an example of one of th ...