I have an express js project generated with npm init, the stack is (express mySql, sequelize), i am planing to do a mern stack starting out from doing backend first. For the database I use MySQL instead of MongoDB.
The error:
the error is can't find module
from local file
here is the snapshot of the error message:
the file structure
package.json
{
"name": "login_system",
"version": "1.0.0",
"description": "",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.1.0",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.1",
"mysql2": "^3.6.0",
"sequelize": "^6.32.1"
}
}
index.js --> entry point
import express from "express";
import db from "./config/database.js";
import router from "./routes/index.js";
const app = express();
// create database connection
try {
await db.authenticate();
console.log("Database Connected ...");
} catch (error) {
console.log(error);
}
app.use(express.json());
app.use(router);
app.listen(5000, () => console.log("server is running at port 5000"));
routes/index.js
import express from "express";
import getUser from "../controllers/Users"; --> this is where the error is
const router = express.Router();
router.get("/users", getUser);
export default router;
controllers/Users.js --> 'cannot find module' error comes from this file
import users from "../models/UserModel";
const getUsers = async (req, res) => {
try {
const users_ = await users.findAll();
res.json(users_);
} catch (error) {
console.log(error);
}
};
export default getUsers;
Any Idea how to solve this error ? thankyou
You need to append .js
to the import statements, for example:
import getUser from "../controllers/Users.js";
import users from "../models/UserModel.js";
As per Node docs:
A file extension must be provided when using the import keyword to resolve relative or absolute specifiers. Directory indexes (e.g. './startup/index.js') must also be fully specified.