0

Hello can I please get some help, I am trying working with MVC on NodeJS so I have created a controller and exported it to my routes and that works just fine but then, when I try to hit the route via post man I get a 404 not found can I please get some help on what I maybe doing wrong.

This is my auth controller with only signup wanted to make this work then add the rest

import { userModel } from "../../Models/Users/Users";
import Bcrypt from "bcrypt";
import Formidable from "formidable";
import nodemailer from "nodemailer";
import dotenv from "dotenv";
dotenv.config();

class userAuth {
  SignUp(request, response) {
    const form = new Formidable.IncomingForm();

    try {
      form.parse(request, async (error, fields, files) => {
        const {
          username,
          firstName,
          lastName,
          email,
          password,
          verifiedPassword,
        } = fields;

        if (
          !username ||
          !firstName ||
          !lastName ||
          !email ||
          !password ||
          !verifiedPassword
        ) {
          return response
            .status(400)
            .json({ msg: "All fields have to be entered" });
        }

        if (password.length < 6) {
          return response
            .status(400)
            .json({ msg: "Password has to be at least 6 characters" });
        }

        if (password !== verifiedPassword) {
          return response.status(400).json({ msg: "Password have to match" });
        }

        const isExistingUserName = await userModel.findOne({
          username: username,
        });

        if (isExistingUserName) {
          return response
            .status(400)
            .json({ msg: "Account with this username already exist" });
        }

        const isExistingEmail = await userModel.findOne({ email: email });

        if (isExistingEmail) {
          return response
            .status(400)
            .json({ msg: "Account with this email already exist" });
        }

        const salt = await Bcrypt.genSalt(15);
        const hashedPassword = await Bcrypt.hash(password, salt);
        const newUser = new userModel({
          username,
          firstName,
          lastName,
          email,
          password: hashedPassword,
        });

        const savedUser = await newUser.save();

        const transporter = nodemailer.createTransport({
          service: "SendinBlue",
          auth: {
            user: process.env.sendinBlue__email,
            pass: process.env.sendinBlue__key,
          },
        });

        const mailOptions = {
          from: process.env.sendinBlue__email,
          to: email,
          subject: "Account Activation",
          html: `

                <h1>Activate your account by clicking on link below<h1>
                <a href="http://localhost:5000/account-activation/${savedUser._id}" target="_blank">Account activation</a>
        
        
            `,
        };

        transporter.sendMail(mailOptions, (error, res) => {
          if (error) {
            return response.status(500).json({
              msg: `Network error please try again later, if error continues contact ${process.envsendinBlue__email}`,
            });
          }

          return response.status(201).json({
            msg: `Email has been sent to ${email} for Account activation`,
          });
        });
      });
    } catch (error) {
      return response.status(500).json({
        msg: `Network error please try again later, if error continues contact ${process.envsendinBlue__email}`,
      });
    }
  }
}

export default userAuth;

This code below is how I am calling the controller in routes

import express from "express";
import userAuth from "../../Controller/UserAuthController/UserAuth";
const router = express.Router();

const userAuthController = new userAuth();

router.post("/api/user-signup", (request, response) => {
  userAuthController.SignUp(request, response);
});

export default router;

Can I please get help on why I am getting 404

Picture showing when I was trying to hit the route in the most basic way without sending anything in body with the hope that I will get a response saying All fields have to be entered from server

postman image

  • Can you add an image of what you are doing in Postman? Also did you try removing the `(request,response)` of the route and just leaving the controller function like `router.post("/api/user-signup", userAuthController.SignUp(request, response));` ?? – Runsis Oct 29 '20 at 14:36
  • Okay let me get the screenshot quick and yes I did try leaving the controller alone like you showed there and I get an error saying the **request and response undefined something like that** – Ntshembo Hlongwane Oct 29 '20 at 14:55
  • @Runsis just added the picture – Ntshembo Hlongwane Oct 29 '20 at 15:01
  • I am sorry I meant `router.post("/api/user-signup", userAuthController.SignUp);` without the (). Can you also add the app.js/index.js file? – Runsis Oct 29 '20 at 15:22
  • Surprisingly works when I write it the way you just wrote if you may please explain if you know how is that working since in my controller class I am taking in parameters i.e **(request, response)** – Ntshembo Hlongwane Oct 29 '20 at 15:59
  • 1
    Well, I was going to write an answer but I can't seem to find the real problem. Anyway try to tidy up your code, instead of creating a class I would create just the file of the controller and use multiple exports for the middleware functions, then by just importing the file you should be fine. The difference between setting the callback with () instead of just the plain name can be explained here https://stackoverflow.com/questions/3246928/in-javascript-does-it-make-a-difference-if-i-call-a-function-with-parentheses . You don't want to call the function straight away but create a reference! – Runsis Oct 29 '20 at 18:44
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/223837/discussion-between-ntshembo-hlongwane-and-runsis). – Ntshembo Hlongwane Oct 29 '20 at 18:48

0 Answers0