I am beginner in NodeJS. I am currently working on NodeJS API project and hosted to Render with node_env
in production.
But in the cloud environment, I received error:
"Error: Cannot find module 'morgan'"
that I guess is one of dev dependency library is not installed.
Initially, I set up the hosting platform build command of installation of libs with npm install
then I changed to npm install --dev
and it able to work.
So my question:
Package.js
"name": "bnndirect_api",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon server"
},
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"express-mongo-sanitize": "^2.2.0",
"express-rate-limit": "^7.1.5",
"helmet": "^7.1.0",
"hpp": "^0.2.3",
"perfect-express-sanitizer": "^1.0.13"
},
"devDependencies": {
"morgan": "^1.10.0",
"nodemon": "^3.0.2"
}
}
My dev code in server.js that uses that lib
const morgan = require("morgan");
// DEV LOGGING MIDDLEWARE
if (process.env.NODE_ENV ===
"development") {
app.use(morgan("dev"));
}
You are using morgan even before it is installed. i.e, in your production environment, you haven't installed morgan. But you have added a require('morgan') statement there which will try to use morgan in your code. You can update your code like this:
// DEV LOGGING MIDDLEWARE
if (process.env.NODE_ENV === "development") {
const morgan = require("morgan");
app.use(morgan("dev"));
}