Receiving no communication from Express Router

Having trouble receiving a response from the server after making get/post requests. I've tried adjusting the order of functions in index.js without success. I also attempted to send a post request using Postman to localhost:8080/register, but the request seems to be stuck.

I suspect that it could be caused by middleware preventing the request from going through. I've even tried commenting out all app.use statements except for authRouter, but it doesn't seem to resolve the issue.

Index.js

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

const db = require('./config/dbConfig');

const app = express();

const authRouter = require('./router/authRouter');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
app.use(authRouter);

const PORT = process.env.PORT || 8080;

db.sync({ force: true }).then(() => {
    app.listen(PORT, () => console.log(`Server up and running @ ${PORT}`));
});

authRouter.js

const { Router } = require('express');
const authController = require('../controllers/authController');
const router = Router();

router.get('/register', () => {
    authController.register_get;
});
router.get('/login', () => {
    authController.signin_get;
});
router.post('/register', () => {
    authController.register_post;
});
router.post('/login', () => {
    authController.signin_post;
});

module.exports = router;

authController.js

module.exports.register_get = (req, res) => {
    res.send('signup');
};

module.exports.register_post = (req, res) => {
    res.send('signup');
};

module.exports.signin_get = (req, res) => {
    res.send('signup');
};

module.exports.signin_post = (req, res) => {
    res.send('signup');
};

Answer №1

When setting up the router.post('/register', ...) method, make sure to pass in a function as the second argument. This function will be called when a client sends a POST request to the /register route.

If you only have one statement inside the route handler function passed to router.post(...), like in the example below:

authController.register_post;

This statement won't do anything. You must actually invoke the register_post function and provide it with the req and res arguments so that it can access the Request and Response objects:

router.post('/register', (req, res) => {
    authController.register_post(req, res);
});

Alternatively, you can simply reference the authController.register_post function directly:

router.post('/register', authController.register_post);

Answer №2

Make sure to actually invoke your controller functions with the correct arguments. Instead of this:

router.get('/register', () => {
    authController.register_get;
});

You should use one of these options:

router.get('/register', (req, res, next) => {
    authController.register_get(req, res, next);
});

or:

router.get('/register', authController.register_get);

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

Navigating File Paths in Node.js

My directory structure is as follows: Main > models > file1.ejs | |> routes > file2.ejs In my code, I'm trying to require file1 from file2 like this: const variable = require("../models/file1.ejs). But what if I don't want to ...

Create Middleware for Managing 401 Error Codes

I am currently utilizing NodeJS version 18.16.1 along with Express version 4.18.2. In my middleware setup, I have the following method where the objective is to redirect to login anytime a 401 response is sent, and optionally include an error message in t ...

How can I work with numerous "Set-Cookie" fields in NextJS-getServerSideProps?

When working with getServerSideProps, I found a way to set multiple cookies on the client device. This is the code snippet that I used: https://i.stack.imgur.com/Kbv70.png ...

What is the trick to ensuring that the bind submit function always works consistently instead of sporadically?

I am attempting to compare two values (min - max) from two input fields. If the min value is greater than the max value, an alert message should be displayed... The issue arises when I correct the max value and submit again, as it continues to show the sa ...

Having difficulty uploading files using FormData in JavaScript, as $_FILES is returning empty

I have implemented a file upload feature to my server using JavaScript, but I am facing an issue with certain jpeg/png files where the $_FILES and $_POST variables are empty. Despite trying various solutions, I haven't been able to resolve this issue. ...

ReactJS | Display or Conceal an Array of Objects depending on a specified condition

The Challenge: I am currently working on a task that involves hiding/showing react elements dynamically based on a property of the constructed Object. To be more specific, let's consider the Array of Objects below: const Apps = [ {name: App1, permi ...

What could be the reason for the undefined return when searching for a statement in MongoLab while using

Currently, I am utilizing Node.js within a Heroku App and connecting to a MongoDB in a MongoLab service. I have inserted a document into a collection on my localhost DB and the next document is stored on MongoLab. { "person": "Jon Smith", "age": 5 ...

Is there a way to output several lines from a JSON file in print form?

I'm working with HTML code that displays multiple lines from a JSON file, but it only shows one line at a time. How can I modify the code to display all users' information? <!DOCTYPE html> <html> <head> <script> function ...

Template is not populating with data (Angular)

Currently, I am honing my Angular skills by working on a simple project. I have been seeking answers to my queries on Stack Overflow as they closely align with the issue I am facing. My challenge lies in displaying asynchronous data before it is initialize ...

Linking an intricate property in ExtJS to a text field

Here is an example of JSON data: { name: { firstname: 'First Name', lastname: 'Last Name' } } How do I go about loading this data into a form field in ExtJS? First Name: [ First Name ] Last Name: [ Last Name ] UPDATE: After imp ...

Dealing with Unwanted Keys When Parsing JSON Objects

Struggling with parsing a list of Objects, for example: After running the code JSON.parse("[{},{},{},{},{}]"); The result is as follows: 0: Object 1: Object 2: Object 3: Object 4: Object 5: Object Expecting an array of 5 objects like this: [Object,Ob ...

"Exploring the world of JavaScript, Ajax, PHP parser errors, and the process of obtaining post data

Having an issue with the AJAX functionality in my game.php file. Despite my efforts to refresh .refre, I keep encountering a "parsererror" message. The jsonString variable is created using JSON.stringify(object). <div class="refre"></div> < ...

Using NodeJS Express to Generate Globally Unique Request Identifiers

Can a distinctive request Id be generated for every log statement without needing to pass the logger to each method or function call? Currently using: NodeJS, Express, Winston ...

The attempted JavaScript socket emissions from the server to the client for listening are currently experiencing difficulties and

I have encountered a peculiar issue with my code. It involves emitting from the server side and listening on the client side. The connection seems to persist indefinitely, even when the client refreshes or exits the page. However, the code on the client si ...

AngularJS ng-include nested form configuration

My application utilizes nested ng-includes. The outer include is a login screen for one application while the inner ng-include includes two templates. The login screen is designed in two steps where the email is checked first and then the password entered. ...

Showing a section of a DIV inside an iframe

I have implemented an HTML object in the following way: <object id="foo" name="foo" type="text/html" data="mypage.aspx"> </object> However, I do not want to display the entire content of mypage.aspx within the HTML object/iframe. In ...

I am facing a recurring issue where I am unable to add new libraries to my node_modules directory due to encountering the same error every time I attempt to

An error occurred after running npm audit --force, causing a dependency issue in my Node_modules 0 verbose cli C:\Program Files\nodejs\node.exe C:\Users\Jenis\AppData\Roaming\npm\node_modules\npm\bin& ...

Tips for receiving alerts on external updates to a mongo collection using sails

Currently, I am in the process of creating an application utilizing mongo and sails. As part of my development, I am investigating how the real-time update feature in sails functions. Although I am currently using sails 0.9.16, I am also curious about ans ...

Error: JSON parsing stopped due to unexpected end of file while attempting to parse data

After testing with other APIs successfully, I found that this particular one is not functioning as expected. const express = require("express"); const https = require("https"); const bodyParser = require("body-parser"); const ...

``There Seems to be an Issue with Loading Content in Tabs

Hey! I'm encountering an issue with my jquery tabs. The first tab content loads fine, but when I select another tab, the content doesn't display. Then, when I try to go back to the first tab, it doesn't load either. Here's the HTML cod ...