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

Enhancing bar chart presentation with text in d3

Looking to enhance my bar chart by adding text tooltips that appear when hovering over each bar. While I am a beginner with d3, I've been struggling to implement this feature effectively. Despite trying various methods gleaned from online resources, t ...

The perplexity of ES6 Promises

Within an asynchronous function, I encountered the following code snippet: await application.save((err) => { console.log("hello"); if (err) { res.status(500).send({ message: "Error encountered" }); } }); conso ...

React JS Material UI disabled button under control

I am looking for some guidance. I am working on a feature where I need to disable a button conditionally. The idea is that if something is selected from my table, then the button should be available; otherwise, it should be disabled. MUI requires a boolean ...

Disappearance of background image on HTML5 canvas upon mouse movement

I am looking to incorporate the ability for users to draw sketches on an image displayed on a canvas. Currently, I am utilizing the sketch.js jQuery library and have encountered the following issues: The image loads successfully onto the canvas. However, ...

Can you explain the term used to describe when specific sections of the source code are run during the build process to improve optimization?

One interesting feature I've noticed in next.js is its automatic code optimization during the build process. This means that instead of running the code every time the app is executed, it's evaluated and executed only once during the build. For ...

What's the deal with blank POST requests in NodeJS?

I am currently facing a puzzling issue with my two NodeJS applications. One of them processes data, while the other sends a POST request with a file attached to an ExpressJS app. Everything seems to be functioning correctly, but I have encountered a strang ...

Display the date in the user interface grid table

I've integrated ui-grid in my project to showcase data along with dates. An example of a date fetched from an ajax call would be: DateReview='06/25/2016' The current format being mm/dd/yyyy for display purposes. The column definition in ...

What is the reason for the JavaScript TypeError (undefined) being triggered when this object is used within a function?

I have defined a new object like this: function node(){ this.tag = null; this.Tdata = []; this.Tchilds = []; } Now, I am trying to use this object in a function: function Validate(root /*Ass ...

Combining two objects in AngularJS to create a new merged object

Is there a way to merge object1 and object2 into object3, updating values corresponding to matching keys while ignoring unmatching keys? var object1 = { "pii" : "val1", "loc" : "val2" } var object2 = { "rrb" : "val3", "voc" : "val4" } var obje ...

The .val() function in jQuery can sometimes give different results when used on input elements with placeholder text in Firefox compared to Chrome

After analyzing the given HTML code, I've noticed discrepancies in the values returned by jQuery in Firefox and Chrome: HTML: <input type="text" name="name" id="name" placeholder="Type Here"> <input type="email" name="email" id="email" plac ...

Revamp the Vue component for better DRYness

Seeking advice on a more efficient way to improve the code below and make it DRY: <h2>{{ title }}</h2> <p>{{ subtitle }}</p> I am currently checking this.name for both the title and subtitle, wondering if there is a better implemen ...

Transmit the image created with node-gd to the recipient

UPDATE: here is the solution that worked for me res.set('Content-Type', 'image/png'); res.end(data, 'binary'). I have been experimenting with generating images dynamically using node-gd in my node.js/express application. Th ...

Transfer information from an Express route to a function exported from a Node module

I'm new to using node.js and I've been told that I need to use middleware, but I'm having trouble understanding its purpose and the proper way to implement it. I have data that is being sent from my view to an express route. ROUTE - route.j ...

Switching from using jQuery.ajax() to fetch() when making requests to a Go REST API endpoint with no payload

I have a ReactJS web application that communicates with a REST API endpoint built in golang. Previously, I used jQuery to make Ajax POST requests and it worked perfectly. Here's an example of the code: // Using jQuery let sendUrl = "http://192.168.1 ...

What could be causing my AJAX code to fail in retrieving information from an API?

Hey everyone, I'm new here and hoping to get some help with an issue I'm facing. I've written a code to fetch data from an API and display it on my HTML page, but for some reason the AJAX code isn't working. There's nothing showing ...

How to Customize the Navbar Position in Bootstrap 3 when the Brand/Logo is Collapsed

I am currently in the process of creating my first website and experimenting with the Bootstrap 3 framework. The navbar I have selected is designed to adjust based on screen size, collapsing into a small button for use on tablets and mobile devices. Howe ...

Clicking on the button has no effect whatsoever

I'm currently dealing with a button on my webpage that seems to be causing me some trouble: <script> function changeMap() { container.setMap(oMap); } </script> <button onClick="changeMap"> Click here </button> Upon inspe ...

Can the browser tabs automatically detect when a user logs out?

When I have multiple tabs open of the same website in a browser, I wonder how other windows can detect when a user has logged out. My development setup involves using Python/Django. The method I am currently implementing is: function user_checking(){ ...

Exploring the Functionality of worker-loader Inline

It was my understanding that the Webpack worker-loader configuration below: ... module: { rules: [ { test: /worker\.js/, loader: "worker-loader", options: { inline: 'fallba ...

React JS - In order to display multiple children, consider utilizing an array rather than individual elements

Currently, I am employing React for my application and utilizing an API located at http://localhost:8080/api/suppliers/supplier/list to fetch data. Upon inspecting the Google Chrome console, this is the format of the data structure I am receiving: 0:{ ...