Express.js encounters a 404 error when router is used

I am currently in the process of learning and consider myself a beginner at Node.js. My goal is to create a basic REST API, but I keep encountering an error 404 when attempting to post data to a specific route using Postman to test if the information has been successfully sent to MongoDB. Despite double-checking all my routes, everything appears to be in order. The strange thing is that the GET request works fine, but the POST request fails to go through.

This is what my app.js looks like:

 (insert JavaScript code)

My model can be found in developer.js:

(insert JavaScript code)

Answer №1

If you want to establish a connection with the database, avoid using

mongoose.connect('mongodb://127.0.0.1:27017');

Instead, use the following:

mongoose.connect('mongodb://127.0.0.0.1:27017/yourDatabaseName');

Refer to the documentation for more information.

Mongoose requires a specific database name in the connect() method.

Your final version of app.js should look like this:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var Developer = require('./models/developers');
var app = express();

// Set up view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use('/', indexRouter);
app.use('/users', usersRouter);

// Connect to Database
mongoose.connect('mongodb://127.0.0.1:27017/my_unique_database_name');

// API Routes
var router = express.Router();

// Prefix routes with /api
app.use('/api', router);

// Handle 404 errors and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// Error handling
app.use(function(err, req, res, next) {
  // Set error parameters based on environment
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // Render error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

// Test Route
router.get('/', function (req, res) {
  res.json({message: 'Welcome to my simple API!'});
});

router.route('/developers')
    .post(function (req, res) {
      var developer = new Developer(); // Create new developer instance
      developer.firstName = req.body.firstName;
      developer.lastName = req.body.lastName;
      developer.jobTitle = req.body.jobTitle;

      developer.save(function (err) {
        if (err) {
          res.send(err);
        } else {
          res.json('Developer was successfully fetched');
        }
      });
    })

    .get(function (req, res) {
      Developer.find(function (err, developers) {
        if (err) {
          res.send(err);
        } else
          res.json(developers);
      });
    });

router.route('/developer/:developer_id')
    .get(function (req, res) {
      Developer.findById(res.params.developer_id, function (err, developer) {
        if (err) {
          res.send(err);
        }
        res.json(developer);
      });
    });

router.route('/developer/firstName/:firstName')
    .get(function (req, res) {
      Developer.find({firstName:res.params.firstName}, function (err, developer) {
        if (err) {
          res.send(err);
        }
        res.json(developer);
      });
    });

Answer №2

It appears that the line app.use('/api', router); may not be effectively serving its intended purpose. When a request is made to the /api endpoint, the code should result in a response following certain operations. However, it seems that the code simply passes the request to the router, which then does nothing with it.

If the createError(404) method includes calls to the res.send() or res.end() methods, it is advisable to move the use() method to the bottom of your code page:

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

This adjustment ensures that it executes after other routes each time.

In my opinion, adhering to a standard coding style enhances the program's readability and flow.

Best of luck.

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

Identifying an Android device using Javascript or jQuery

Is there a way to identify an Android device for styling a mobile website? I want to add specific CSS styles for users on the Android platform. Appreciate any help! ...

How can I loop the keyframe animation across various elements of an SVG file simultaneously?

After creating an animation using CSS and SVG, I am experiencing different parts of it animating in and out. My goal is to have the animation start from the top once it's finished. There are multiple keyframes involved since I'm animating variou ...

What is the best method for exporting a MapboxGL map?

I am currently utilizing mapboxGL to display maps on a website, and I am interested in exporting the map as an image with the GeoJSON data that has been plotted. I attempted to use the leaflet plugin for this purpose, but it was unable to render clusters ...

What could be causing the incorrect updating of React State when passing my function to useState?

Currently, I am in the process of implementing a feature to toggle checkboxes and have encountered two inquiries. I have a checkbox component as well as a parent component responsible for managing the checkboxes' behavior. The issue arises when utiliz ...

The concept of setting a value is not defined in JavaScript when compared to

Within my primary python script, the following code snippet is present. @app.route('/accounts/test/learn/medium') def medium(): word = random.choice(os.listdir("characters/")) return render_template('accounts/test/medium.html', word=w ...

Performing calculations within handsontable

Trying to figure out how to concatenate values from a handsontable grid, I stumbled upon some code on jsfiddle that caught my eye. Here is the link: http://jsfiddle.net/9onuhpn7/4/ The task at hand involves 3 columns A,B,C and an attempt to concatenate ...

Dividing a string by lines in NodeJS and converting it into an object

I am currently working on reading the contents of a file that has the following format: one-apple two-banana three-orange My goal is to extract a key-value object from this data. However, my current implementation only returns an empty object: var regex ...

Creating a custom Webpack 5 configuration for an Express application

I am facing an issue while setting up a new react app template using webpack 5 and express. Every time I run the build command, I encounter the following error: ✖ 「wds」: Invalid configuration object. Webpack has been initialized using a configuratio ...

Utilize a Python script to transmit data to JavaScript through JSON in order to dynamically alter the content of

Currently, I am developing an interactive display that utilizes sensors on a raspberry pi. The display is set to show a webpage and I have implemented a python script to handle sensor interaction. My goal is to change the displayed web page when a user p ...

Angular 2 - synchronizing timer for all users

I have developed a timer that needs to function consistently for all users at the same time. To achieve this, I stored the start_time (timestamp when the timer begins) in my database and implemented the following code snippet to calculate the remaining ti ...

experiencing difficulty in transmitting HTML content through nodemailer

I'm having trouble sending HTML-formatted text in emails using nodemailer. exports.send = function(req, res) { console.log(req.query); var mailOptions = { to: req.query.email, subject: req.query.sub, text: 'Date of Interview: ' ...

The method mockImplementation cannot be found on the busboyConstructor object

Despite extensive research, I have yet to find a solution to my problem. Whenever I attempt to mock busboy in my project using jest, I keep encountering an error stating that mockImplementation (and mockRestore) is not a function. import * as Busboy from ...

Interact with HTML Radio Buttons to Trigger Input Opening

I need to have a message saying "We're sorry..." and a "black box" displayed only when the radio button is set to YES, otherwise keep it hidden. Can I achieve this using JavaScript only, or is there a way to do it with HTML alone? <h3 >Did you ...

An issue arises when attempting to utilize the 'push()' method to append a string to a JSON array

I am looking to append strings to my JSON file structure shown below: { "items": [] } To achieve this, I have the requirement of using the following code: var items = require("../../config/item.json"); The approach I am taking is ...

Retrieving information using URL parameters

Having a good understanding of Express, I'm curious if Sinatra offers a similar feature to what I utilize in my Express applications. For instance, consider this code snippet from Express: app.param('userId', function(req, res, next, id) { ...

techniques for accessing HTML source code through an AJAX call

I am trying to retrieve the HTML source of a specific URL using an AJAX call, Here is what I have so far: url: "http://google.com", type: "GET", dataType: "jsonp", context: document.doctype }).done(function ...

Upon completing the NodeJS update, an error appears stating: "Unable to load the gRPC binary module."

After receiving a warning that my current Node version (7.10) was not supported in my FireBase project, I decided to update it using npm. However, when I tried running my server on localhost, I encountered the following error: Error: Failed to load gRPC b ...

Autocomplete feature in Material-UI does not trigger the onChange event when a chip

I've encountered a quirk with the Material UI Autocomplete component. It seems that when I delete a tag directly from the chip using the (x) button, the onchange function of the autocomplete isn't triggered. Does anyone know how I can ensure that ...

Is there a way to forward to the "current" page in node.js without using middleware?

Users have the ability to log in from any page on the website. I am trying to implement a feature where the login form redirects to the current page the user is on and clears the POST data to avoid refresh problems. Despite my efforts, I have not been ab ...

"We are experiencing issues with the app.get function and it is

Although my backend is successfully serving other files, I have encountered an issue with loading new files that are located in a folder named js within the directory. These specific files are not being loaded, and despite spending an hour trying to troubl ...