'ERR_MODULE_NOT_FOUND' when I try to move code to another file and use module.exports in express

I am very new to backend development and am trying to split the code from my server.js file into corresponding named files for the appropriate actions. I want to move my code for the register post request into its own file.

I have tried exporting it like in examples online, but I cannot seem to do it right and my app cannot run properly until I figure out what I am doing wrong. Below is the code from the new file and the original server.js file. I will add explicit comments around the register post request area to stand out, but will include all the code incase it contains needed context for why I am not able to get past this error.

import express from "express";
import bcrypt from "bcrypt-nodejs";
import cors from "cors";
import knex from "knex";
import { handleRegister } from "./controllers/register";



const db = knex({
  client: "pg",
  connection: {
    host: "127.0.0.1",
    port: 5432,
    user: "cassiusreynolds",
    password: "",
    database: "smart-brain",
  },
});

// * EXPRESS SETUP
const app = express();
app.use(cors());
app.use(express.json());

// * GET REQUEST TEST
app.get("/", (req, res) => {
  res.send('success');
});

// * SIGN IN
app.post("/signin", (req, res) => {
  const { email, password } = req.body;
  db.select("email", "hash")
    .from("login")
    .where("email", "=", email)
    .then((data) => {
      const isValid = bcrypt.compareSync(password, data[0].hash);

      if (isValid) {
        return db
          .select("*")
          .from("users")
          .where("email", "=", email)
          .then((user) => {
            res.json(user[0]);
          })
          .catch((err) => res.status(400).json("unable to get user"));
      } else {
        res.status(400).json("wrong credentials entered");
      }
    });
});

// !!!!!!!!!!!!!!!!!PROBLEM AREA!!!!!!!!!!!!!!!!//
// * REGISTER
app.post("/register", handleRegister(req, res, db, bcrypt));
// !!!!!!!!!!!!!!!!!PROBLEM AREA!!!!!!!!!!!!!!!!//

app.get("/profile/:id", (req, res) => {
  const { id } = req.params;
  db.select("*")
    .from("users")
    .where({ id })
    .then((user) => {
      if (user.length) res.json(user[0]);
      else res.status(400).json("Not found");
    })
    .catch((err) => res.status(400).json("error getting user "));
});

// * IMAGE PUT REQ
app.put("/image", (req, res) => {
  const { id } = req.body;
  db("users")
    .where("id", "=", id)
    .increment("entries", 1)
    .returning("entries")
    .then((entries) => {
      res.json(entries[0].entries);
    })
    .catch((err) => res.status(400).json("error counting photo tally"));
});

// * RUN SERVER
app.listen(3001, () => {
  console.log("app is running on port 3001");
});

Below is the code inside the new register.js file

const handleRegister = (req, res) => {
  const { email, name, password } = req.body;
  const hash = bcrypt.hashSync(password);
  // transaction makes sure tables wont fall out of sync
  // if one is able to be updated and the other is not
  db.transaction((trx) => {
    trx
      .insert({
        hash: hash,
        email: email,
      })
      .into("login")
      .returning("email")
      // first update the login table, then we get the login email
      // now we update the users table in a promise
      .then((loginEmail) => {
        return (
          trx("users")
            .returning("*")
            .insert({
              name: name,
              email: loginEmail[0].email,
              joined: new Date(),
            })
            .then((user) => {
              res.json(user[0]);
            })
            .then(trx.commit)
            .catch(trx.rollback)
            // must commit the updates to see changes
            .catch((err) => res.status(400).json("unable to join"))
        );
      });
  });
};

module.exports = handleRegister;
  • can you actually see “handleRegister” from this import statement, i would say you are not, right?!
  • you might also want to looks at what “default” and “named” exports looks like in nodejs

happy coding :slight_smile:

1 Like