I just solved this error myself, and I will provide the code to show how I fixed it.
To begin, I have 3 files in play here.
- index.js (the file that calls the API)
- user-router (where the post takes place)
- user-control (where the details of the post are defined)
The error was raised from this file, particularly line 5, where I am importing the router.
//index.js
const express = require("express");
const cors = require("cors");
const db = require("./db/connection");
const userRouter = require("./routes/user-router"); //PROBLEMATIC LINE
const app = express();
const apiPort = 3000;
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use(express.json());
db.on("error", console.error.bind(console, "MongoDB connection error:"));
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.use("/api", userRouter);
Clearly, the post function is what is throwing the error. However, after reading through this Stack Overflow thread, I learned that the problem has to do with the connections between the files - the imports and exports of functions. This led me to look in the control folder.
//user-router.js
const express = require("express");
const UserCtrl = require("../control/user-control"); //PROBLEMATIC LINE (2)
const router = express.Router();
router.post("/user", UserCtrl.createUser); //PROBLEMATIC LINE(1)
module.exports = router;
What I found was that the module.exports line was the issue. What I needed to do was wrap the export in curly braces and the problem went away.
//user-controller.js
const User = require("../models/user-model");
createUser = async (req, res) => {
//...
};
//module.exports = createUser; //PROBLEMATIC LINE
module.exports = { createUser }; //This fixed the problem
I hope that by showing you the entire breakdown of my problem, you are able to solve yours. Also, I hope that by using my limited knowledge to try to answer a question, I can build up a few reputation points, so that I am able to respond to comments and such, LOL. Let me know if this was able to help you.