POSTMAN requests are being rejected by the Express API

I've been working on creating an API for a MEAN stack application that handles user registration and authentication. However, I've run into a strange issue where the API is not responding to any requests made through Postman, not even a simple '/' get request with a response.

Below is my index.js file:

const exp = require('express');
const bp = require('body-parser');
const { success, error } = require('consola')
const { connect } = require('mongoose');

// Importing app constants
const { DB, PORT } = require("./config");

// Initialize the application
const app = exp();

// Set up middleware
app.use(cors());
app.use(bp.json);

// User Router Middleware
app.use("/api/users", require("./routes/users"));
app.use("/basic", require("./routes/basic"));

// Connect to the database

const startApp = async () => {
    try {
        // Connect to DB
        await connect(DB, {
            useFindAndModify: true,
            useUnifiedTopology: true,
            useNewUrlParser: true
        });

        success({
            message: `Successfully connected with the Database \n${DB}`,
            badge: true
        });

        // Start server on PORT
        app.listen(PORT, () =>
            success({ message: `Server started on PORT ${PORT}`, badge: true })
        );
    } catch (err) {
        error({
            message: `Unable to connect with Database \n${err}`,
            badge: true
        });
        startApp();
    }
};



startApp();

My basic routing is as follows, but it's also not working for me:


router.get('/', function (req, res) {
    res.send('Hello World!' + req.body)
})

module.exports = router;

The Postman response shows an error, which you can see in the screenshot below:

https://i.sstatic.net/TXU40.png

Although the server seems to be running, it is rejecting all requests.

mongodb://localhost:27017/node-auth

SUCCESS  Server started on PORT 3000                                                 16:26:36  

Answer №1

Have you included the express module in your basic router setup?
It should be set up as follows:

 const express = require("express");
 const router = express.Router();
  
 router.get("/", (req, res) => {
   res.send(`Hello World! ${req.body}`);
 });
          
 module.exports = router;

Answer №2

Apologies for the oversight.

I neglected to include the () brace, which was causing the application to run improperly. It's amazing what a fresh pair of eyes can catch.

Previously: app.use(bp.json); Now: app.use(bp.json());

Functioning flawlessly at this point.

Answer №3

The express instance in index.js is not being utilized for the router

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

How can I display a file located within the /views/subfolder/ directory using Node JS and Express?

I'm facing an issue with rendering .ejs files in Node JS + Express. Despite my efforts to troubleshoot by researching, I couldn't find a solution. That's why I'm reaching out here for help! The task at hand is simple - I want to render ...

Error occurred due to an unexpected end of JSON input following a pending promise

I am currently developing a data handler that requires downloading a file for parsing and processing within the handler. To handle this, I have implemented the file request within a promise and called it asynchronously from other methods. Including the h ...

Retrieve the JSON data based on a specific key after a specified period

Hello there, I am encountering an issue with a specific JSON key. Let's say I have an external file containing JSON data structured like this: { "key 1":[ { "linkName":"key name 1.1", "linkUrl":"key URL 1.1" }, ...

I am looking for a highly specialized jQuery selector that fits my exact requirements

Hello everyone, I'm encountering an issue with a jQuery selector. Here is the HTML code snippet: <div id="Id_Province_chzn"> <a href="javascript:void(0)" class="chzn-single chzn-default" tabindex="-1"> <span> + this.default_tex ...

Effective ways to manage extensive forms in Angular 2

I have a complex form in my application. What is the most effective way to collect data from this form and transmit it to the API using Angular 5? ...

The ng-click event for the reset button is limited to a single use

There seems to be a problem with the reset button functionality on my webpage. Although it initially works, it only works once and then requires a reload of the page to function again. Here is the JS code: var ctrl = this; var original_device = angular.c ...

Having trouble with submitting an Ajax form to a MySQL database

My expertise lies in PHP and HTML, but I'm currently learning JavaScript. I'm facing a challenge with creating a form that can submit data to be inserted into MySQL without reloading the page (using AJAX). Here is the form I have: <form id=" ...

I'm struggling with my project called "Number TSP" and I can't seem to figure out why it's not working properly

Upon reaching the end of my code, I am encountering an issue where instead of seeing the expected output of "Done!", it displays undefined. This is the code in question: const container = document.querySelector(".container") const table = document.querySe ...

JavaScript error: Function is not defined when using Paper.js

UPDATE the problem has been solved by making the colorChange function global I am attempting to modify the color of the path when the 'Red' button is clicked using the colorChange function. Despite my efforts, I keep getting an error stating tha ...

What are the steps to automatically populate the location or name in the trip advisor widget?

I have encountered an issue with my website where I have multiple hotel lists but the trip advisor widget only shows one. Is there a solution, such as a script or other method, that can use variables to automatically set the location or name in the widget? ...

Exploring the functionalities of JavaScript methods and nested components within Vue.js

Learning Vue.js has been an interesting experience for me. However, I am facing challenges with methods and child elements in the library. It seems like there is something simple that I am overlooking. In my current project, I have list items rendered on ...

The property 'body' cannot be read because it is undefined

I have been attempting to incorporate passport logic into my controllers file, but I encountered an issue. When I place the logic inside the controllers, it gives me an error message saying "Cannot read property 'body' of undefined." However, whe ...

What is the best way to wait for a series of subscriptions to complete?

I am currently facing challenges with Observables while working on a complex REST API query function that involves intricate logic and multiple requests and responses. Although I have already written numerous functions with subscriptions like the ones bel ...

Developing a nested JSON structure

I'm struggling with a seemingly simple task of creating a JSON object. Despite my efforts, I can't seem to find the right information to guide me through it. Here is what I have so far: var myJsonObject = new Object(); myJsonObject.context.appli ...

Comparing GraphQL Dataloader with Mongoose Populate

When it comes to performing a join-like operation, both GraphQL and Mongoose can be utilized for achieving the desired outcome. Before posing any inquiries, consider the following example related to Task/Activities (please note that this code is purely fo ...

When utilizing styled-jsx alongside postcss, experiencing issues with styles failing to reload or rebuild

I'm currently using postcss in conjunction with styled-jsx. In my setup, I have multiple CSS files that I'm importing using the @import directive within the _app.js file. Everything seems to work smoothly, except when I modify any of the CSS file ...

Is it necessary to include parentheses when utilizing a named function as a jQuery ajax success callback?

Is it necessary to include parentheses when specifying a function as a success callback if it was defined earlier? What impact does including or not including parentheses have? For example: function fish_food(){//do something} $.ajax({ url: '/ ...

Creating new rows dynamically with jQuery

In my current setup, there is a table with one row and two columns - a textbox and a button: $(function() { var i = 1; $('#add').click(function() { i++; $('#dyn').append('<tr id="row' + i + '">&l ...

I keep encountering a parse error when trying to parse JSON that contains a numerical key

After receiving data in JSON format from a Java application, I encountered a parse error when the key was of type Long: 1: { "CONGESTION": 1, "ANSWER": 7 } However, after changing the key to a String as shown below: "1": { ...

The system considers the resource as a script, yet it was transmitted with the MIME type of text

I am encountering an issue when trying to integrate AngularJS/JavaScript into my HTML document. Each time I try to load my index.html file, the following error message appears: Resource interpreted as Script but transferred with MIME type text/html: "http ...