Webpack Compiles With Errors After Computer Restart - node.js

*** Updated with new errors,
After running
webpack --display-error-details
I get a more detailed error. please notice it appears to be looking for node_modules going backwards in directories out of my project.
Module not found: Error: Can't resolve 'html' in
'/Users/wuno/Dropbox/google/devops/htdocs/riverwalk' BREAKING CHANGE:
It's no longer allowed to omit the '-loader' prefix when using
loaders.
You need to specify 'html-loader' instead of 'html'. resolve 'html' in '/Users/wuno/Dropbox/google/devops/htdocs/riverwalk'
Parsed request is a module using description file:
/Users/wuno/Dropbox/google/devops/htdocs/riverwalk/package.json
(relative path: .) after using description file:
/Users/wuno/Dropbox/google/devops/htdocs/riverwalk/package.json
(relative path: .)
resolve as module
/Users/wuno/Dropbox/google/devops/htdocs/node_modules doesn't exist or is not a directory
/Users/wuno/Dropbox/google/devops/node_modules doesn't exist or is not a directory
/Users/wuno/Dropbox/google/node_modules doesn't exist or is not a directory
/Users/wuno/Dropbox/node_modules doesn't exist or is not a directory
/Users/wuno/node_modules doesn't exist or is not a directory
/Users/node_modules doesn't exist or is not a directory
/node_modules doesn't exist or is not a directory
I have been working on an Angular 2 express app for a few months and have dealt with the common webpack breaking for no reason. Normally I delete the node_modules folder and run npm install which fixes any issues. This time without changing anything webpack will not compile.
I pushed my project to git. Everything was working great. I shut my computer down to go to a meeting. Once I opened everything back up and ran webpack I get an error which states Can't resolve html in... This error appears for every component in my project. One for each separate view. This is a exact error for the first page it throws on,
ERROR in ./assets/app/layouts/public.component.ts
Module not found: Error: Can't resolve 'html' in '/Users/wuno/Dropbox/google/devops/htdocs/mypp'
# ./assets/app/layouts/public.component.ts 25:18-52
# ./assets/app/app.module.ts
# ./assets/app/main.ts
I am at a loss for how to proceed here. I even cloned my git repo at my last working push and it throws the same errors when running webpack.
This is my webpack config file,
var webpackMerge = require('webpack-merge');
var commonConfig = require('./webpack.config.common.js');
module.exports = webpackMerge(commonConfig, {
devtool: 'cheap-module-eval-source-map',
output: {
path: './public/js/app',
publicPath: "/js/app/",
filename: 'bundle.js',
chunkFilename: '[id].chunk.js'
}
});
Angular components are at
/assets/app/
index.html is at,
/public/index.html
This is my app.js in the root directory,
var express = require('express');
var models = require('./models/');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var appRoutes = require('./routes/index');
// api controllers
var authors = require('./controllers/authors');
var books = require('./controllers/books');
var books = require('./controllers/address');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'public'));
app.set('view engine', 'hbs');
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/public')));
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
next();
});
// Route app to index.html and hand off to angular2
app.use('/', appRoutes);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
return res.render('index');
});
models.sequelize
.authenticate()
.then(function () {
console.log('Connection successful');
})
.catch(function(error) {
console.log("Error creating connection:", error);
});
module.exports = app;
Any help would be appreciated. At the very least how can I debug this further?

Related

Using Twig render engine with Express

I've decided to make the jump from building my websites with slim, php and twig to using node.js and express.
To limit the shock of changing my whole process I want to keep using slim as the template engine instead of the default jade.
I have tried to change the code to change the render engine over to twig but now I am getting the following error message. Does anyone know what I am doing wrong? I am at a loss as to why it is not working. Any help would be very helpful.
Error message:
Error: Failed to lookup view "error" in views directory "/var/www/html/SocialTrackers/app/views"
at Function.render (/var/www/html/SocialTrackers/app/node_modules/express/lib/application.js:580:17)
at ServerResponse.render (/var/www/html/SocialTrackers/app/node_modules/express/lib/response.js:1008:7)
at /var/www/html/SocialTrackers/app/app.js:38:7
at Layer.handle_error (/var/www/html/SocialTrackers/app/node_modules/express/lib/router/layer.js:71:5)
at trim_prefix (/var/www/html/SocialTrackers/app/node_modules/express/lib/router/index.js:315:13)
at /var/www/html/SocialTrackers/app/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/var/www/html/SocialTrackers/app/node_modules/express/lib/router/index.js:335:12)
at next (/var/www/html/SocialTrackers/app/node_modules/express/lib/router/index.js:275:10)
at Layer.handle_error (/var/www/html/SocialTrackers/app/node_modules/express/lib/router/layer.js:67:12)
at trim_prefix (/var/www/html/SocialTrackers/app/node_modules/express/lib/router/index.js:315:13)
This is the code I am currently running. Other than changes to shift over the using twig as the render engine, I have made no other changes to the initial express install.
app.js
var createError = require('http-errors');
var twig = require("twig");
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'twig');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bootstrap', express.static(__dirname + '/node_modules/bootstrap/dist/'))
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Additionally, I am the following file structure (default express)
app
--bin
--node_modules
--public
--routes
----index.js
----users.js
--views
----error.twig
----index.twig
----landingpage.twig
--app.js
Took me a few days to figure this one out.
As I said I'm new to Nodejs and express so I believe I made a very rookie mistake. I thought I would post the solution incase anyone else has this issue.
I was running the node server on a ec2 instance. While I was updating the code it turns out I had to restart the node server as well.
I'm using pm2 to keep the server running all the time so for me the solution was to run the following command.
pm2 restart [namespace of server]
Note: for me, I never gave the server a namespace so it was simply 'default'. If you don't know the namespace you can find it by running 'pm2 list'
pm2 restart default

NodeJS, Express, and ejs; why does the test fail, but the view works?

I'm working through a PluralSight course/project on NodeJs and Express. They have a project template with tests. The app is working, it is actually finding and rendering the view. But the test for setting the views directory is failing. I have tried many variations of directories for the views, with and without the '/' after the '/views'; I have tried many variations of using the path.join(__dirname, './src/views') as well. Nothing seems to satisfy the test, even when I tried using the same values in the test, as in app.set('views', path.join(__dirname, '../../src/views')) Nothing seems to satisfy the test.
The tests are run with npm run test:module1. When that runs there is a line in the console: mocha --exit './test/module1/*.spec.js' The test is definitely finding the app because it runs 8 tests; 7 pass and only this one fails.
But I'm trying to re-learn modern JS, as well as Express and ejs, so I may be missing something basic.
Here's my app.js code:
const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
app.set('views', './src/views');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, '/public/')))
app.get('/', function(req, res) {
res.render('index', { title: 'Index'});
})
app.listen(3000, function() {
console.log('PS Project Running on port 3000!');
});
and here's their relevant test:
const path = require('path');
describe('View engine and directory', () => {
it('should set view engine and directory #app-set-views-directory-engine', () => {
assert(typeof app === 'function', '`app` const has not been created in `app.js`.');
assert(app.settings['view engine'] === 'ejs', 'The view engine has not been set to `ejs`.');
assert(app.settings.views === path.join(__dirname, '../../src/views'), 'The view directory has not been set to the `views` directory.');
});
});

No content in <app-root> element in browser using the command "node app.js"

I created an Angular 7 application using the Angular CLI. I added my express server as one knows it. Afterwards I used the command "node server/app.js to start my app, but then in the browser in the "Elements" section there appears <app-root></app-root> without any content. As if the browser knew nothing about the actual Angular application. And when I run the ng serve command it seems to know about the actual Angular application, but there appears a 404 not found error in terms of post and get requests to the data server.
I already had a working Angular4 application with -I guess- the same setup and now same things seem to not work any longer.
I researched all day long to find the solution but for nothing.
I think it is not advantageous to post all my files in here. Comment if I was wrong and I am going to edit them.
Thanks in advance.
My app.js:
"use strict";
var bodyParser = require('body-parser');
const cors = require('cors');
// import { Observable } from 'rxjs';
var express = require("express");
var path = require("path");
var app = express();
app.use(cors());
const router = express.Router();
var nodeModulesPath = path.join(__dirname, "..", "node_modules");
app.use("/node_modules", express.static(nodeModulesPath));
var srcPath = path.join(__dirname, "..", "src");
app.use("/src", express.static(srcPath));
var serverPath = path.join(__dirname);
app.use("/server", express.static(serverPath));
// app.use(bodyParser.json());
var models = require("./models");
models.sequelize.sync({force:true}).then(function() {
console.log("TABELLE ERSTELLT");
// app.use(cors());
app.use("/", router);
app.use(bodyParser
.urlencoded({extended:true})
);
app.use(bodyParser.json());
console.log("after bodyparser");
app.get("/", function(req,res){
res.sendFile(path.join(__dirname, "views", "index.html"));
});
// app.get('/*', function(req, res) {
// res.sendFile(path.join(__dirname, "views", "index.html"));
// });
app.post("/goals/create",function (req, res){
models.Goal.create({
id: req.body.id,
name: req.body.name,
content: req.body.content,
firstGivenValue: req.body.firstGivenValue,
fittingValue: req.body.fittingValue,
someone_would_like_to_implement: req.body.someone_would_like_to_implement,
i_know_how_to_implement_it: req.body.i_know_how_to_implement_it
}).then(function(obj){
console.log(obj.id);
// res.end("erfolgreich");
res.redirect("/");
})
console.log(req.body);
});
app.get("/test",(req, res) => {
res.end("test erfolgreich");
});
app.listen(3000);
});
You mention that you think it used to work for angular 4. Currently you're serving the index.html from the src folder. That's not going to work, your app is a typescript app and will need to be compiled one way or another; not to mention the Angular compiler. In the early days (I think pre 4, but not sure) angular serve also write the served files in a folder in your project, so you could just pick those JIT compiled files up and toss them on a web server, or express server. Those days are gone (with good reason for that matter, mostly performance).
You will now have to create an explicit build (ng build) and tell your express server (app.js) to target your dist folder.
TL;DR:
Run ng build
Replace
var srcPath = path.join(__dirname, "..", "src");
app.use("/src", express.static(srcPath));
With:
var distPath = path.join(__dirname, "..", "dist");
app.use("/dist", express.static(distPath));

Use `index.html` rather than `index.ejs`

I have a mean-stack application. By going to https://localhost:3000/#/home, it reads views/index.ejs. Here is the setting in app.js:
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.all('/*', function(req, res, next) {
res.sendFile('index.ejs', { root: __dirname });
});
Actually, I don't use the feature of ejs in index.ejs. So now I want to use just a index.html rather than index.ejs.
I put the content of index.ejs in public/htmls/index.html and views/index.html. And here is the current setting in app.js:
var app = express();
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.all('/*', function(req, res, next) {
res.sendFile('index.html', { root: __dirname });
// res.sendFile('index.html'); // does not work either
});
However, running https://localhost:3000/#/home returns
Error: No default engine was specified and no extension was provided.
Does anyone know how to fix it?
Edit 1: by following the answer of user818510, I tried res.sendFile('index.html', { root: path.join(__dirname, 'views') }); in app.js, it still can NOT find index.html.
Whereas, in routes/index.js, the following can find index.html, but it gives a warning express deprecated res.sendfile: Use res.sendFile instead routes/index.js:460:9.
var express = require('express');
var router = express.Router();
var path = require('path');
... ...
router.get('*', function(req, res) {
res.sendfile('./views/index.html'); // works, but a deprecation warning
// res.sendFile('index.html', { root: path.join(__dirname, 'views') }); does not work
});
It is really confusing...
If it's a single page mean application, then you only need to start express with static and put index.html in static/ dir :
Project layout
static/
index.html
server.js
server.js
'use strict';
var express = require('express');
var app = express();
app.use(express.static('public'));
var server = app.listen(8888, function () {
console.log("Server started. Listening on port %s", server.address().port);
});
Now you can call http://localhost:8888/#home
It looks like a problem with the path. Your index.html is located at public/htmls/index.html and views/index.html. Your root option in res.sendFile should be __dirname+/public/htmls/ or __dirname+/views
In your code, you are using the path:
res.sendFile('index.html', { root: __dirname });
Your app.js would be in the project root where you have public directory alongside at the same level. Based on your rootoption in res.sendFile, you would have to place index.html at the same level as your app.js.
You should change the root path in res.sendFile. Use:
res.sendFile('index.html', { root: path.join(__dirname, 'public', 'htmls') });
OR
res.sendFile('index.html', { root: path.join(__dirname, 'views') });
The above root is based on the path that you've mentioned in your question.
Here's the link to the docs:
http://expressjs.com/en/api.html#res.sendFile
Your no default engine error is probably because you have commented the line where you set the view engine to ejs but still have existing ejs views. Uncommenting that line with the root path change should solve your issue.
Do not serve static content from an application server.
Use a web server for that, and in production, a content delivery network like Akamai.
A content delivery network will charge you per bandwidth (e.g: 10 cents per Terabyte). Serving the equivalent of 10 cents in Akamai can cost you thousands of dollars using cloud instances.
In addition to that, your servers will have unnecessary load.
If you absolutely have to serve static content from your application servers, then put a reverse proxy cache like nginx, varnish or squid in front of your server. But that will still be very cost inefficient. This is documented in the express website.
This is common practice in every Internet company.

Error: Failed to lookup view in Express

Note: my auto answer at end of the post
I'm trying to make a better experience of nodeJS and i don't really like to get all the script in one file.
so, following a post here i use this structure
./
config/
enviroment.js
routes.js
public/
css/
styles.css
images
views
index
index.jade
section
index.jade
layout.jade
app.js
My files are right now:
app.js
var express = require('express');
var app = module.exports = express.createServer();
require('./config/enviroment.js')(app, express);
require('./config/routes.js')(app);
app.listen(3000);
enviroment.js
module.exports = function(app, express) {
app.configure(function() {
app.use(express.logger());
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
app.set('view engine', 'jade'); //extension of views
});
//development configuration
app.configure('development', function() {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
//production configuration
app.configure('production', function() {
app.use(express.errorHandler());
});
};
routes.js
module.exports = function(app) {
app.get(['/','/index', '/inicio'], function(req, res) {
res.render('index/index');
});
app.get('/test', function(req, res) {
//res.render('index/index');
});
};
layout.jade
!!! 5
html
head
link(rel='stylesheet', href='/css/style.css')
title Express + Jade
body
#main
h1 Content goes here
#container!= body
index/index.jade
h1 algoa
The error i get is:
Error: Failed to lookup view "index/index"
at Function.render (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\application.js:495:17)
at render (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\response.js:614:9)
at ServerResponse.render (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\response.js:638:5)
at c:\xampp\htdocs\nodejs\buses\config\routes.js:4:7
at callbacks (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\router\index.js:177:11)
at param (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\router\index.js:151:11)
at pass (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\router\index.js:158:5)
at Router._dispatch (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\router\index.js:185:4)
at Object.router [as handle] (c:\xampp\htdocs\nodejs\buses\node_modules\express\lib\router\index.js:45:10)
at next (c:\xampp\htdocs\nodejs\buses\node_modules\express\node_modules\connect\lib\proto.js:191:15)
But i don't really know what is the problem...
I'm starting thinking is because the modules exports...
Answer:
Far away the unique solution i found is to change the place i defined app.set('views') and views engine
I moved it to the app.js and now is working well.
var express = require('express');
var app = module.exports = express.createServer();
require('./config/enviroment.js')(app, express);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
require('./config/routes.js')(app);
app.listen(3000);
I don't really understand the logic behind this but i gonna supose it have one.
Adding to #mihai's answer:
If you are in Windows, then just concatenating __dirname' + '../public' will result in wrong directory name (For example: c:\dev\app\module../public).
Instead use path, which will work irrespective of the OS:
var path = require ('path');
app.use(express.static(path.join(__dirname + '../public')));
path.join will normalize the path separator character and will return correct path value.
npm install express#2.5.9 installs the previous version, if it helps.
I know in 3.x the view layout mechanic was removed, but this might not be your problem. Also replace express.createServer() with express()
Update:
It's your __dirname from environment.js
It should be:
app.use(express.static(__dirname + '../public'));
It is solved by adding the following code in app.js file
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.get('/', function(req, res){
res.render("index");
});
I had the same error at first and i was really annoyed.
you just need to have ./ before the path to the template
res.render('./index/index');
Hope it works, worked for me.
You could set the path to a constant like this and set it using express.
const viewsPath = path.join(__dirname, '../views')
app.set('view engine','hbs')
app.set('views', viewsPath)
app.get('/', function(req, res){
res.render("index");
});
This worked for me
Check if you have used a proper view engine.
In my case I updated the npm and end up in changing the engine to 'hjs'(I was trying to uninstall jade to use pug).
So changing it to jade from hjs in app.js file worked for me.
app.set('view engine','jade');
In my case, I solved it with the following:
app.set('views', `${__dirname}/views`);
app.use(express.static(`${__dirname}/public`));
I needed to start node app.min.js from /dist folder.
My folder structure was:
This problem is basically seen because of case sensitive file name.
for example if you save file as index.jadge than its mane on route it should be "index" not "Index" in windows this is okay but in linux like server this will create issue.
1) if file name is index.jadge
app.get('/', function(req, res){
res.render("index");
});
2) if file name is Index.jadge
app.get('/', function(req, res){
res.render("Index");
});
use this code to solve the issue
app.get('/', function(req, res){
res.render("index");
});
Just noticed that I had named my file ' index.html' instead for 'index.html' with a leading space. That was why it could not find it.
This error really just has to do with the file Path,thats all you have to check,for me my parent folder was "Layouts" but my actual file was layout.html,my path had layouts on both,once i corrected that error was gone.
i had the same problem but, i change the name of the file from index.html to index.ejs and works!!!!
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.render('index');
});
router.get('/contact', (req, res) => {
res.render('contact', { title: 'Contact Page' });
});
module.exports = router;
and index.js
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const app = express();
//settings
app.set('port', 4000);
app.set('views', path.join(__dirname,'views'));
app.set('view engine', 'ejs');
//middlewares
//routes
app.use(require('./routes'));
//static files
//listening
app.listen(app.get('port'), () => {
console.log('Server is running at http://localhost:'+app.get('port')+'/');
});
update:
add this in index:
app.engine('html', require('ejs').renderFile);
I change the views folder name to views_render and also facing the same issue as above, so restart server.js and it works for me.
I had the same issue and could fix it with the solution from dougwilson: from Apr 5, 2017, Github.
I changed the filename from index.js to index.pug
Then used in the '/' route: res.render('index.pug') - instead of res.render('index')
Set environment variable: DEBUG=express:view
Now it works like a charm.
I had this issue as well on Linux
I had the following
res.render('./views/index')
I changed it too
res.render('../views/index')
Everything is now working.
I had the same issue. Then just check the file directory in your explorer. Sometimes views folder isn't present.
In my case, I was deploying my web app on a Windows Server and I had a service set up to run a .bat file with only one line as content:
node D:\webapp\app.js
But this was not enough. I also had to change the directory before that, so I added the following line at the beginning of the .bat file:
cd D:\webapp
app.get("/", (req, res) => {
res.render("home");
});
// the code below brought the error
app.get("/", (req, res) => {
res.render("/");
})
I was facing this error because i mistakenly deleted my error.ejs file and it was being called in app.js file and was not found in views as it was already deleted by me

Resources