How to solve Error : cannot find module "ejs"? - node.js

I started a new (and first) express.js project using ejs but facing to this following error while accessing to the page :
Error: Cannot find module 'ejs '
Require stack:
- C:\wamp64\www\myproject\node_modules\express\lib\view.js
- C:\wamp64\www\myproject\node_modules\express\lib\application.js
- C:\wamp64\www\myproject\node_modules\express\lib\express.js
- C:\wamp64\www\myproject\node_modules\express\index.js
- C:\wamp64\www\myproject\server.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:925:15)
at Function.Module._load (node:internal/modules/cjs/loader:769:27)
at Module.require (node:internal/modules/cjs/loader:997:19)
at require (node:internal/modules/cjs/helpers:92:18)
at new View (C:\wamp64\www\myproject\node_modules\express\lib\view.js:81:14)
at Function.render (C:\wamp64\www\myproject\node_modules\express\lib\application.js:570:12)
at ServerResponse.render (C:\wamp64\www\myproject\node_modules\express\lib\response.js:1012:7)
at C:\wamp64\www\myproject\server.js:10:13
at Layer.handle [as handle_request] (C:\wamp64\www\myproject\node_modules\express\lib\router\layer.js:95:5)
at next (C:\wamp64\www\myproject\node_modules\express\lib\router\route.js:137:13)
Here is how I proceed from the beginning :
Created a new folder called myproject
Created a new file called server.js
node init
Modified package.json to add nodemon
npm install --save nodemon
npm install --save express
npm install --save ejs
My file server.js :
var app = require('express')();
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
res.setHeader('Content-Type', 'text/plain');
res.send('Accueil');
})
.get('/album', function(req, res){
res.setHeader('Content-Type', 'text/plain');
res.render('album.ejs ', {name :'yop'});
})
.use(function(req, res, next){
res.setHeader('Content-Type', 'text/plain');
res.status(404).send('Page introuvable !');
});
app.listen(8080);
My file package.json :
{
"name": "myproject",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.5",
"express": "^4.17.1",
"nodemon": "^2.0.6"
}
}
My project's structure :
My project directory
node_modules folder
views folder
album.ejs file
package.json
server.js

You add one extra space accidentally behind the ejs.
res.render('album.ejs ', {name :'yop'});
Remove that space like below.
res.render('album.ejs', {name :'yop'});
And you could just use the file name without extension name.
res.render('album', {name :'yop'});

in your server.js
app.set('view engine', 'ejs')
app.set('views', __dirname + '/views')

add this to your code just below app.set('view engine', 'ejs)
app.engine('ejs', require('ejs').__express);

If you already had installed ejs, you must uninstall and install it again
Here are the steps:
npm uninstall ejs --save
npm install ejs --save

Related

Heroku app showing blank page. react / express/ node

https://peaceful-basin-17224.herokuapp.com/
Of course, "it works on my machine".
When I look at the network, I see the assets being loaded from index.html but nothing else.
Also, for some reason the npm run build doesn't seem to run. I'll heroku bash into the app and I won't find a /frontend/build
I've been messing with this since last night and feel like I haven't made any progress. Any help would be appreciated!
Part of my server.js
app.use(express.static(path.join(__dirname, '/frontend')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, '/frontend/public', 'index.html'));
});
app.use(express.static(__dirname +'frontend'));
//Serve static assests if in production
if(process.env.NODE_ENV === 'production'){
//Set static folder
app.use(express.static('frontend/build'));
app.get('*', (req, res)=>{
res.sendFile(path.resolve(__dirname, 'frontend', 'public', 'index.html')) });
}
Here's my package.json:
{
"name": "backend",
"version": "1.0.0",
"description": "",
"proxy": "http://localhost:3001",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js",
"server": "nodemon server.js",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix frontend && npm run build"
},
"author": "",
"license": "ISC",
"dependencies": {
"#mailchimp/mailchimp_marketing": "^3.0.69",
"express": "^4.17.1",
"simple-react-modal": "^0.5.1"
}
}
I think you can delete all of this code:
app.use(express.static(path.join(__dirname, '/frontend')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, '/frontend/public', 'index.html'));
});
app.use(express.static(__dirname +'frontend'));
//Serve static assests if in production
if(process.env.NODE_ENV === 'production'){
//Set static folder
app.use(express.static('frontend/build'));
app.get('*', (req, res)=>{
res.sendFile(path.resolve(__dirname, 'frontend', 'public', 'index.html')) });
}
and put only this:
app.use(express.static(path.join(__dirname, './frontend/build')));
My react.js folder had the name "frontend" and it was at the same level with my server.js file, that's why it is one dot ./frontend/build. And don't remove build name and dont change it to any other name.
And please let me know if this answer helps.

Failed at the app#1.0.0 start script This is probably not a problem with npm. There is likely additional logging output above

Hi Guys, I have created a little project of Mern stack. I am deploying it correctly on Heroku. But as soon as I am checking her on Heroku after deploying, then Failed to load resource: the server responded with a status of 503 (Service Unavailable) error is coming.
But as soon as I run heroku local in cmd after deploying then it is working correctly. I am giving below the heroku setup code. Please guide me. please ........
package.sjon file of backend
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "npm install && node index",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"dependencies": {
"config": "^3.3.1",
"express": "~4.16.1",
"express-fileupload": "^1.1.7-alpha.3",
"mongoose": "^5.9.12",
"nodemailer": "^6.4.6"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Index.js file of backend
var express = require('express');
var path = require('path');
const connectDB = require('./config/db')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var studentRouter = require('./routes/student')
var app = express();
connectDB();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('client/build'))
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
app.use('/', indexRouter);
app.use('/', studentRouter);
app.use('/users', usersRouter);
if (process.env.NODE_ENV == "production") {
app.use(express.static('client/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
}
var port = process.env.PORT || '8000';
app.listen(port, () => {
console.log(`server run port ${port}`);
})
module.exports = app;
All these codes are absolutely correct. I had a problem creating a cluster in mongodb atlas. The problem was that I had selected add current ip address while creating the cluster. Whereas I had to select allow from anywhere. So now I have selected the book. And now it is doing the right thing.
In my case, changing network access form anywhere in my MongoDB cluster, fixed the problem.
Also, don't forget to hit restart all dynos.

How to build next.js production?

I try to get a production build in next.js to run it on my server but I can't build next.js production build when I try
npm run build
Does anyone know how to get a prod build in next.js working correctly I did everything in the next.js documentation but always get this error below. If I do a dev build it works just fine but trying prod build results in errors.
I did also next build many times and reinstalled all node_modules packages still having this error.
it always shows me in terminal
Error: Could not find a valid build in the '/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/.next' directory! Try building your app with 'next build' before starting the server.
at Server.readBuildId (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next-server.js:753:15)
at new Server (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next-server.js:80:25)
at module.exports (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next.js:6:10)
at Object.<anonymous> (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/next.config.js:6:13)
at Module._compile (internal/modules/cjs/loader.js:707:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10)
at Module.load (internal/modules/cjs/loader.js:605:32)
at tryModuleLoad (internal/modules/cjs/loader.js:544:12)
at Function.Module._load (internal/modules/cjs/loader.js:536:3)
at Module.require (internal/modules/cjs/loader.js:643:17)
at require (internal/modules/cjs/helpers.js:22:18)
at loadConfig (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/config.js:47:28)
at _callee2$ (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/build/index.js:52:42)
at tryCatch (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:62:40)
at Generator.invoke [as _invoke] (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:288:22)
at Generator.prototype.(anonymous function) [as next] (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:114:21)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! hello-next#1.0.0 build: `next build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the hello-next#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/kk/.npm/_logs/2018-12-10T19_58_00_588Z-debug.log
server.js
const express = require("express");
const next = require("next");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV === "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
next.config.js
const express = require("express");
const next = require("next");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV === "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get("/projects/:page", (req, res) => {
const page = req.params.page;
let file = "";
switch (page) {
case "example1":
file = "/projects/example1";
break;
case "example2":
file = "/projects/example2";
break;
}
return app.render(req, res, file, { page });
});
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
package.json
{
"name": "hello-next",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"dev": "node server.js",
"build": "next build",
"export": "next export"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#zeit/next-sass": "^1.0.1",
"express": "^4.16.4",
"next": "^7.0.2",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"redux": "^4.0.1",
"video-react": "^0.13.1"
}
}
If anyone has an idea would be so nice! I plan to run this next.js site using node on my AWS server. But to do this I need to get production build of react.js currently I can run just a development build.
Hope someone has an idea.
Thanks in advance!
next build followed by next start should be the right commands to prepare the build for production and run it.
Here's an example for package.json. if you want to export application to run as a static content, something like hosting it in s3 as a static website, you need to run next export
...
"scripts": {
"build": "next build",
"start": "next start",
"export": "next export"
}
...
Make sure you have the above scripts in your package.json then run the following in order
$ npm run build
$ npm run start
If you want to start application with specific port, you can specify -p port as argument for npm run command
npm run start -- -p 3232
If you want to incorporate this into a CI/CD pipeline, you need to have Dockerfile, here's a simple example
FROM node:alpine
#copy source
COPY . /app
# Install deps
RUN cd /app && npm install
# Build
RUN npm run build
ENTRYPOINT [ "npm", "run", "start" ]
Still need more explanation or help, don't hesitate to leave a comment and I will be more than happy to assist.
Seems your server.js config is not correct. Please try moving all you have from your next.config.js to server.js make sure the next.config.js file is empty then create a new npm run script:
"prod_start": "NODE_ENV=production node server.js"
Your package.json should then look like this:
{
"name": "hello-next",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"dev": "node server.js",
"build": "next build",
"prod_start": "NODE_ENV=production node server.js",
"export": "next export"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#zeit/next-sass": "^1.0.1",
"express": "^4.16.4",
"next": "^7.0.2",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"redux": "^4.0.1",
"video-react": "^0.13.1"
}
}
make sure to run: npm run build && npm run prod_start
Then you should have a production build of react running using next.js
Let me know if you got question.
You must launch next build at your root folder and not inside .next/
There are 3 ways todo it:-
way 1: use next build instead of npm run build
way 2: npm run build npm install -g serve serve -s build
more info: https://create-react-app.dev/docs/deployment/
way 3: after npm run build, Remove / from JS,CSS links from /static/index.html file. eg. replace these 2 lines
<script defer="defer" src="/static/js/main.aa87bc08.js"></script>
<link href="/static/css/main.073c9b0a.css" rel="stylesheet"/>
with these 2 lines
<script defer="defer" src="static/js/main.aa87bc08.js"></script>
<link href="static/css/main.073c9b0a.css" rel="stylesheet" />
now it even work on file:///D:/codes/ProjectName/build/index.html
tell me in the comments if none of the 3 ways work, I'll find, try & tell way 4, 5, etc.

Node.js web app crashes when deployed to heroku

This problem has probably been posted about a dozen times, but I can't find a single fix to my problem.
Here is my code:
//////////////////// VARIABLES ////////////////////
//use express
var express = require('express');
//variable to use express
var app = express();
//use the body-parser middleware to handle post data
var bodyParser = require('body-parser');
//create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//create a variable for the server
//var server = require('http').Server(app)//
//////////////////// SETUP ////////////////////
//tells express to use ejs as the view/template engine
app.set('view engine', 'ejs');
//use express as middleware to serve static pages
app.use('/CSS', express.static('CSS'));
app.use('/images', express.static('images'));
//////////////////// FUNCTIONALITY ////////////////////
//sets index as the default page
app.get('/', function (req, res) {
res.render('index');
});
//serve specified pages
app.get('/:page', function (req, res) {
res.render(req.params.page);
});
app.post('/custom_rec', urlencodedParser, function (req, res) {
console.log(req.body);
res.render('custom_rec', {data: req.body});
});
const host = '0.0.0.0';
const port = process.env.PORT || 5000;
app.listen(port, host, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
Here are the relevant logs:
2018-10-23T08:42:25.388218+00:00 heroku[web.1]: State changed from crashed to starting
2018-10-23T08:42:30.109913+00:00 heroku[web.1]: Starting process with command `node ./index.js`
2018-10-23T08:42:33.503841+00:00 heroku[web.1]: Process exited with status 1
2018-10-23T08:42:33.525464+00:00 heroku[web.1]: State changed from starting to crashed
2018-10-23T08:42:33.439948+00:00 app[web.1]: module.js:549
2018-10-23T08:42:33.439965+00:00 app[web.1]: throw err;
2018-10-23T08:42:33.439967+00:00 app[web.1]: ^
2018-10-23T08:42:33.439968+00:00 app[web.1]:
2018-10-23T08:42:33.439970+00:00 app[web.1]: Error: Cannot find module '/app/index.js'
2018-10-23T08:42:33.439972+00:00 app[web.1]: at Function.Module._resolveFilename (module.js:547:15)
2018-10-23T08:42:33.439973+00:00 app[web.1]: at Function.Module._load (module.js:474:25)
2018-10-23T08:42:33.439975+00:00 app[web.1]: at Function.Module.runMain (module.js:693:10)
2018-10-23T08:42:33.439976+00:00 app[web.1]: at startup (bootstrap_node.js:191:16)
2018-10-23T08:42:33.439978+00:00 app[web.1]: at bootstrap_node.js:612:3
Here is my Procfile:
web: node ./index.js
Here is my package.json:
{
"name": "anirec",
"version": "1.0.0",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "hidden"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "hidden"
},
"homepage": "hidden",
"description": "",
"dependencies": {
"body-parser": "^1.18.3",
"ejs": "^2.6.1",
"express": "^4.16.4"
},
"engines": {
"node": "8.11.4"
}
}
Here is an image of my directory:
The app works using local host.
I've tried having my server listen to 'process.env.PORT'. I've tried taking out "main" in my package.json. I've tried a relative path in my Procfile. I've tried reinstalling node_modules. My Procfile is in the same directory as index.js.
What else am I missing? Thanks in advance.
Edit: I've also tried restarting the server/dyno. 'Index.js' is also listed when I type 'git ls-files' into my terminal.
You have case-sensitive issue, your Index.js starts with capital letter, it should be index.js instead.

How to run project in Angular 4/expressJS server directly(without webpack)

for now I exec 'ng build' and exec 'ts-node ./src/index.ts':
//////////index.ts
import * as express from 'express';
import { join } from 'path';
import { json, urlencoded }from 'body-parser';
import BaseRoutes = require("./backend/services/newService");
var app : any = express();
app.use(express.static(join(__dirname + '/../dist/')));
app.use(json());
app.use(urlencoded({extended: true}));
app.use('/api', new BaseRoutes().routes);
app.get('*', function(req, res, next) {
res.sendFile(join(__dirname + '/../index.html'));
});
app.listen(3000);
all good and work, but How to run only expressJS server, compile project by using original files only (without webpack).
in case of pushing on prod I compile project by compressed /dist/files only, otherwise I would like to work with original files
varibale __dirname is
C:\Users\AxOn\Documents\projects\techStarters\ang4Express\src
Help please
if I exec just 'ts-node ./src/index.ts' and change path as __dirname + '/index.html' I see white Display:
seems angular is not loaded.
in your package.json
{
"name": "project-name",
"version": "0.1.0",
"private": true,
"scripts": {
"start": "node ./server.js"
},
"dependencies": {...
then in your project directory at the command line do;
npm start
npm will execute whatever is in start section of your package.json file

Resources