What could be causing the malfunction in the routing system?

Using postman, when attempting to POST for user registration with the endpoint

"http://localhost:3000/register?name=USER1&<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="61f4fcf0f8fdac8484948795c0948494829798fdfcc7faf6f4">[email protected]</a>&password=pass1"
, it appears that the routing is not functioning correctly. What could be causing this issue?

Errors: Postman displays Cannot POST /register. Apart from that, no errors are observed and the server operates fine on port 3000.

App.js

require('dotenv').config();  
const passport = require('passport');
require("./app_api/passport")
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
const userRoutes = require("./app_api/routes/index");

 
mongoose
  .connect(   
    "mongodb://127.0.0.1:27017"  
    , {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true}
  )  .then(() => {
    console.log("Connected to database!");
  })
  .catch(() => {
    console.log("Connection failed!");
  });
 
app.use(passport.initialize());  
app.use((req, res, next) => {  
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"  
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, PUT, DELETE, OPTIONS"
  );
  next();
});

app.use("/register", userRoutes);

module.exports = app;

./routes/index.js

const express = require("express");
const ctrlAuth = require("../../controllers/authentication");
const router = express.Router();

router.post('/register', function(req, res){ctrlAuth.register});
router.post('/login', function(req, res){ctrlAuth.login});

module.exports = router;

./controllers/authentication.js

const passport = require('passport');
const mongoose = require('mongoose');
const User = require('../schema/user');  

const register = (req, res) => {
  if (!req.body.name || !req.body.email || !req.body.password) {  
  return res
  .status(400)
  .json({"message": "All fields required"});  
  const user = new User();
  user.name = req.body.name;
  user.email = req.body.email;
  user.setPassword(req.body.password);
  user.save((err) => {  
  if (err) {  
  res  
  .status(404)
  .json(err);
  } else {  
  const token = user.generateJwt();
  res  
  .status(200)  
  .json({
    token  
    ,message: "User created!"  
  });
  }
  });
};

module.exports = { 
register
};

const login = (req, res) => {
  if (!req.body.email || !req.body.password) {
  return res
  .status(400)
  .json({"message": "All fields required"});
  }
  passport.authenticate('local', (err, user, info) => {
  let token;
  if (err) {
  return res
  .status(404)
  .json(err);
  }
  if (user) {
  token = user.generateJwt();
  res
  .status(200)
  .json({token});
  } else {
  res
  .status(401)
  .json(info);
  }
  })(req, res);
  };


  module.exports = {
    
    login
    };

Answer №1

modify the functions in ./controllers/authentication.js as shown below:

const passport = require("passport");
const mongoose = require("mongoose");
const User = require("../schema/user");

const registerUser = (req, res) => {
  if (!req.body.name || !req.body.email || !req.body.password) {
    return res.status(400).json({ message: "All fields are required" });
  }
  const user = new User();
  user.name = req.body.name;
  user.email = req.body.email;
  user.setPassword(req.body.password);
  user.save((err) => {
    if (err) {
      res.status(404).json(err);
    } else {
      const token = user.generateJwt();
      res.status(200).json({
        token,
        message: "User created successfully!",
      });
    }
  });
};

const loginUser = (req, res) => {
  if (!req.body.email || !req.body.password) {
    return res.status(400).json({ message: "All fields are required" });
  }
  passport.authenticate("local", (err, user, info) => {
    let token;
    if (err) {
      return res.status(404).json(err);
    }
    if (user) {
      token = user.generateJwt();
      res.status(200).json({ token });
    } else {
      res.status(401).json(info);
    }
  })(req, res);
};

exports.registerUser = registerUser;
exports.loginUser = loginUser;

also make changes to your App.js, and remove /register from the route:

require('dotenv').config();  
const passport = require('passport');
require("./app_api/passport");
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
const userRoutes = require("./app_api/routes/index");

 
mongoose
  .connect(   
    "mongodb://127.0.0.1:27017"  
    , {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true}
  )  .then(() => {
    console.log("Connected to database!");
  })
  .catch(() => {
    console.log("Connection failed!");
  });
 
app.use(passport.initialize());  
app.use((req, res, next) => {  
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"  
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, PUT, DELETE, OPTIONS"
  );
  next();
});

app.use("/", userRoutes);

module.exports = app;

update the router as follows:

const express = require("express");
const authController = require("../../controllers/authentication");
const router = express.Router();

router.post('/register', authController.registerUser);
router.post('/login', authController.loginUser);

module.exports = 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

Retrieve the updated value following an updateOne() operation

Is it feasible to retrieve all updated values or values with a difference after calling updateOne()? _.each(gameResult, function(gameResult){ bulk.find({"user" : gameResult.user, "section" : gameResult.section , "code" : gameResult.code}).upsert().up ...

I am attempting to utilize a ref in React to access an element within a MUI modal, but I am encountering issues as the reference to the

I've been encountering an issue while trying to access the component did mount lifecycle method, as it's showing null. Interestingly, when I remove the modal, everything works as expected. However, inside the modal, the ref isn't functioning ...

Flask application experiencing issues with loading CKEditor

Currently, I am working in PyCharm to develop a basic web application. My goal is to use CKEditor to allow for customization of certain form elements. To provide some context, here is the complete directory structure: <Root> -<app> -< ...

What is the best way to dynamically filter categories using PHP?

I am in the process of developing a website and I'm looking to implement content filtering by TYPE, SIZE, and other criteria similar to how it's done on eBay. Since I am new to working with PHP, I would appreciate if anyone could share some code ...

Tips for ensuring that divs resize to match the container while preserving their original proportions:

#container { height: 500px; width: 500px; background-color: blue; } #container>div { background-color: rgb(36, 209, 13); height: 100px; } #one { width: 1000px; } #two { width: 800px; } <div id="container"> <div id="one">&l ...

Achieving a continuous 2-layer css parallax background in Firefox using css properties "transform" and "perspective" while ensuring the background remains visible beyond content height

You are my final hope. I made a decision to add an update to the Page of my brother's store. One of the new features I wanted was a simple parallax background with two layers to create a sense of depth while scrolling. At first, I managed to make it ...

Updating a calendar page in Rails 4 using AJAX technology

Currently, I am utilizing jQuery's datepicker functionality to display a calendar. The intended behavior is that upon clicking on a specific date, the page should generate relevant information (in this case, a table showcasing available seating) assoc ...

Utilizing AJAX to send HTTParty requests in Rails

I am a newcomer to both Rails and AJAX. My goal is to access an API hosted on a different website, but I encountered issues with cross-origin HTTP requests. To overcome this obstacle, I decided to utilize HTTParty. Within the code snippet below, I am inst ...

The getStaticProps function in Next.js does not pass any data back to the pages

After setting up my hosted database, I encountered an issue with fetching data from it. Despite confirming that the database is running smoothly through the Swagger app, no data appears when called via API form. import React from 'react'; export ...

What is the best way to locate the path to an item in Node.js?

I am currently working with node/express and attempting to implement solutions I have come across, such as those found in this discussion: Display Pdf in browser using express js Unfortunately, I am struggling to determine the correct path to my PDF file. ...

Upon inputting the text value, the concealed button will automatically appear without the need to press any buttons

I would like to create something similar. The hidden button should appear after entering the text value without the need to press any buttons. For example, if a user enters Hazrat Shahjalal International Airport, Dhaka (DAC), the button will become visibl ...

Rejection of HTML notifications reset

When working on my web app that utilizes HTML Notifications, I encountered an issue. Everything functions properly if the user allows notifications for the first time and begins using them. However, if the user initially blocks the notification by clicking ...

Tips for using Node.js and Express to upload and access a file

Despite reading numerous posts on this topic, I am still struggling to understand how to upload a *.csv file and process its contents. Below is my jade file: //views/import.jade extends layout block content h1= title form(action="/import", method="post", ...

Is it possible to invoke a JavaScript function within a React.js application?

I am currently working on converting an HTML template to React JS. In my JavaScript file, I have defined some functions. However, when I try to call one of these functions in React JS, I encounter an error. 'abc' is not defined no-undef Here ...

Move a <div> using a handle (without using JQuery)

I devised a plan to create a moveable div with a handle and came up with this code snippet: var mydragg = function() { return { move: function(divid, xpos, ypos) { divid.style.left = xpos + 'px'; divid.style.top = ypos + &apo ...

Tips for recognizing when Vuetify's v-autocomplete has reached the final scrolled item

I am working with a Vuetify v-autocomplete component and I need to implement a feature where I can detect when the user reaches the last item while scrolling, in order to load more items without the user having to manually type for search: // component.vue ...

What could be the reason behind the occurrence of an error after deleting certain lines of code

The code below is functioning correctly. obj = { go: function() { alert(this) } } obj.go(); // object (obj.go)(); // object (a = obj.go)(); // window (0 || obj.go)(); // window However, an error arises when I comment out the first two lines. obj ...

The function FormatCurrency is non-existent

I need assistance with converting a textbox value into a currency using the jquery.formatCurrency-1.4.0.js plugin. My JavaScript function is set up like this: $(document).ready(function() { $('.currency').blur(function() { $(&apo ...

Exploring Inner Elements with jQuery Click Function

Here is a link to my interactive code example: http://jsfiddle.net/zqegh7yz/1/. The HTML markup in the example looks like this: <ul class="list"> <li class="clickable">item 1 <ul> <li>subitem 1</li> ...

The Bootstrap modal form fails to properly handle the POST method when sending data to the server

I am encountering an issue with a button that triggers a modal form <a href="#" class="btn btn-primary" data-toggle="modal" data-target="#agregarProducto">Add Material</a> The modal appears as shown below: https://i.stack.imgur.com/J39x9.pn ...