I have been deploying my app to Azure for a few weeks now without problem. However now that I've integrated the DB to the backend it is throwing this error seen in the log stream and giving the browser a 500 code.
Application has thrown an uncaught exception and is terminated:
Error: Cannot find module 'async/each'
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (D:\home\site\wwwroot\node_modules\mongoose\lib\schema.js:11:12)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
Mongoose appears to be the issue, and so when I exclude it then all is fine again. I tried including async-each as a dependency in my package.json but that's not helped (I've not seen a module with a / in before so was guessing here)
Also in a moment of desperation I've tried pushing the same app to another Web App service but it failed to even deploy. WebApiClient timed out - whatever THAT means.
I deployed the exact same app to Heroku and it works perfectly.
"use strict";
let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
let mongoose = require('mongoose');
let passport = require('passport');
let LocalStrategy = require('passport-local').Strategy;
let session = require('express-session');
//routes
let home = require('./routes/index');
let register = require('./routes/register');
let members = require('./routes/members');
let login = require('./routes/login');
let logout = require('./routes/logout');
let app = express();
app.locals.courses = require('./data/courses');
// uncomment after placing your favicon in /public
//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(session({secret:'anything'}));
app.use(passport.initialize());
app.use(passport.session());
//mongoose passport config
require('./db').then(mongoose => {
mongoose.Promise = global.Promise;
require('./models/user').then(User => {
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
});
})
//allow CORS requests
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use('/', home);
app.use('/register', register);
app.use('/members', members);
app.use('/login', login);
app.use('/logout', logout);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.send(err.message);
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.send(err.message);
});
module.exports = app;
I deployed mongoose successfully to Azure, and the test code also worked well. Maybe your application will use any module which is configured in devDependenciessection in package.json file.
As Azure Web Apps as a production web server, if you deploy your app via git, be default the deployment task will run npm install --production, which will ignore the dependencies in develop mod.
So, you can try to follow Custom Deployment Script to generate the deplotment script for node.js and modify deploy.cmd, find sentence call :ExecuteCmd !NPM_CMD! install --production and modify to call :ExecuteCmd !NPM_CMD! install.
Meanwhile, you can follow https://learn.microsoft.com/en-us/azure/nodejs-specify-node-version-azure-apps to upgrade your node.js and npm version of Azure Web Apps' runtime, to avoid the nested node_modules folder structure.
Related
Hello I am getting an error when trying to start my server. This is what it says :
D:\Other\Projects\Code\Powershell\shopping-cart\node_modules\express\lib\router\index.js:139
debug('dispatching %s %s', req.method, req.url);
^
TypeError: Cannot read property 'method' of undefined
at Function.handle (D:\Other\Projects\Code\Powershell\shopping-cart\node_modules\express\lib\router\index.js:139:34)
at router (D:\Other\Projects\Code\Powershell\shopping-cart\node_modules\express\lib\router\index.js:47:12)
at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\app.js:7:39)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Module.require (internal/modules/cjs/loader.js:1044:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\bin\www:7:11)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
My app.js file :
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var routes = require('./routes/index')(passport);
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var expressHbs = require('express-handlebars');
var mongoose =require('mongoose');
var app = express();
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var bodyParser = require('body-parser');
mongoose.connect('mongodb://localhost:27017/shopping', {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.connection.on('error', err => {
throw 'failed to connect to MongoDB';
});
require('D:/Other/Projects/Code/Powershell/shopping-cart/config/passport.js');
// view engine setup
app.engine('.hbs', expressHbs({defaultLayout: 'layout', extname:'.hbs'}))
app.set('view engine', '.hbs');
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({secret: 'mysupersecret', resave: false, saveUninitialized: false}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
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;
And my index.js file :
var express = require('express');
var router = express.Router();
var Product = require('D:/Other/Projects/Code/Powershell/shopping-cart/models/product');
var csrf = require('csurf');
//var passport = require('D:/Other/Projects/Code/Powershell/shopping-cart/config/passport.js');
var passport = require ('passport');
var csrfProtection = csrf();
router.use(csrfProtection);
/* GET home page. */
router.get('/', function(req, res, next) {
Product.find(function(err, docs) {
var productChunks = [];
var chunkSize = 3;
for (var i = 0; i < docs.length; i += chunkSize) {
productChunks.push(docs.slice(i, i + chunkSize));
}
res.render('shop/index', { title: 'Shopping Cart', products: productChunks });
});
});
router.get('/user/signup', function (req, res, next) {
res.render('user/signup', {csrfToken: req.csrfToken()});
});
router.post('/user/signup', passport.authenticate('local.signup', {
successRedirect: '/user/profile',
failureRedirect: '/user/signup',
failureFlash: true
}));
router.get('/user/profile', function(req, res, next) {
res.render('user/profile');
});
module.exports = router;
Any hints on what could be the issue? I checked the lines that are being mentioned in the thrown error and can not find anything that is broken, and I have also checked other questions on this error, none that helped me. Any help is appreciated , thanks!
From the stack trace, it looks like the problem is caused by this line:
var routes = require('./routes/index')(passport);
If you look in your routes/index.js, you are exporting a router with:
module.exports = router;
Well, the problem is that you can't call router(passport). That's not a legit way to use a router. I can't tell what you were really trying to do with that. I would assume you want to hook your routes into the app with something like:
app.use(routes)
But, maybe you had some other intention there. In any case, router(passport) isn't something you can do.
FYI, it is a very useful skill to learn how to read these stack traces. You're typically looking to start at the top of the stack trace and go down line by line until you find a line of code that's in your own source file (your code that triggered this). Then, go examine that exact line with the context of what the eventual error was and see if you can then see what's wrong with that line of code or with the parameters used in that line of code.
I have updated all dependancy in my package.json , and installed all the needed ones.
And i have tried from youtube and edited my app.js file
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var expressValidator = require('express-validator');
var LocalStrategy = require('passport-local').Strategy;
var multer = require('multer');
var upload = multer({dest: './uploads'});
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Handle Sessions
app.use(session({
secret:'secret',
saveUninitialized: true,
resave: true
}));
// Passport
app.use(passport.initialize());
app.use(passport.session());
// Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
But when i am trying to run the file by putting
npm start command
These error comes
C:\nodeproject\nodeauth\app.js:45
app.use(expressValidator({
^
TypeError: expressValidator is not a function
at Object.<anonymous> (C:\nodeproject\nodeauth\app.js:45:9)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Module.require (internal/modules/cjs/loader.js:849:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (C:\nodeproject\nodeauth\bin\www:7:11)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
at internal/main/run_main_module.js:17:11
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! nodeauth#0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the nodeauth#0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
I have even checked for the Express Validator module , but it seems nothing is working out.
See below example
// ...rest of the initial code omitted for simplicity.
const { check, validationResult } = require('express-validator');
app.post('/user', [
// username must be an email
check('username').isEmail(),
// password must be at least 5 chars long
check('password').isLength({ min: 5 })
], (req, res) => {
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
User.create({
username: req.body.username,
password: req.body.password
}).then(user => res.json(user));
});
I'm trying to catch the post data from my form and when I'm done with processing I want it to render the index.html file again.
Although when I'm trying the code as displayed below, I get an error.
The error:
Error: Cannot find module 'html'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
at new View (/Applications/XAMPP/xamppfiles/htdocs/controlpanel/node_modules/express/lib/view.js:81:14)
at Function.render (/Applications/XAMPP/xamppfiles/htdocs/controlpanel/node_modules/express/lib/application.js:570:12)
at ServerResponse.render (/Applications/XAMPP/xamppfiles/htdocs/controlpanel/node_modules/express/lib/response.js:1008:7)
at /Applications/XAMPP/xamppfiles/htdocs/controlpanel/server.js:14:9
at Layer.handle [as handle_request] (/Applications/XAMPP/xamppfiles/htdocs/controlpanel/node_modules/express/lib/router/layer.js:95:5)
at next (/Applications/XAMPP/xamppfiles/htdocs/controlpanel/node_modules/express/lib/router/route.js:137:13)
The code:
var express = require('express');
var session = require('express-session');
var app = express();
app.use('/public', express.static('public'));
app.use( express.static('public/html') );
app.post('/', function(req, res, next) {
console.log('start processing postdata...');
next()
});
app.all('/', function(req, res) {
res.render('html/index.html');
});
app.listen(2222);
Everything works fine for the GET method.
Only the POST request is causing this error.
What am I doing wrong?
Thanks in advance, Laurens
Here is the working code, you should use sendFile instead if render. Render is been used with views.
'use strict';
let express = require('express');
// let session = require('express-session');
let app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/public', express.static('public'));
app.use(express.static('public/html'));
app.post('/', function (req, res, next) {
console.log('start processing post data...');
next();
});
app.all('/', function (req, res) {
res.sendFile('./index.html', {
root: __dirname + '/public/html'
});
});
app.listen(2222);
I have setup new express (nodejs) project and while I tried to run url it shows me an error of 404 not found error. Yet I have not modified any single line of code and directory structure. I have used express-generator command to create express project's structure.
Can anyone provide me suggestions for following issues?
- Why default code does not run?
- How should I setup my project directory to prevent write this long url.
- How could I integrate my chat application with yii1 project.
Following are my code details.
URL : http://localhost:3000/wchat/wnode/users
Directory structure :
wchat/wnode/users
wchat : php project
wnode : node directory to implements instant notification and chat
users : module
Code files :
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//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('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
Error :
Not Found
404
Error: Not Found
at app.use.res.render.message (/var/www/html/wchat/wnode/app.js:30:13)
at Layer.handle [as handle_request] (/var/www/html/wchat/wnode/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:312:13)
at /var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:330:12)
at next (/var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:271:10)
at /var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:618:15
at next (/var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:256:14)
at Function.handle (/var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:176:3)
at router (/var/www/html/wchat/wnode/node_modules/express/lib/router/index.js:46:12)
Looking at your routes,
app.use('/', routes); -> handlers GET on localhost:3000
app.use('/users', users); -> handles GET on localhost:3000/users
So there is nothing to handle localhost:3000/wchat/wnode/users. Hence the 404.
If you want to handle something like localhost:3000/wchat/wnode/users,
you need to have a route like
router.verb('/wchat/wnode/users', function (req, res, next) {
// handle whatever you want.
});
Looking at your code and what url you are trying to GET, i would really suggest to familiarize yourself with how express handles routing. More info here
I have carefully examined my app.js file in the project root directory, but I cannot find app.listen or the server object that gets running for npm start. Everything works fine except that, but I need the server object in order to use socket.io. I've tried setting it up manually but it ends up with an error saying that the port (3000) is in use. Can you specify which line or method contains app.listen? This template was generated using express-generator and I have made only a few modifications.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var http = require('http');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__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('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Below is the error log
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1042:14)
at listen (net.js:1064:10)
at Server.listen (net.js:1138:5)
at Function.app.listen (/Users/Lee/Desktop/bwall/node_modules/express/lib/application.js:556:24)
at Object.<anonymous> (/Users/Lee/Desktop/bwall/bin/www:7:18)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
Your error is saying that you're already using port 3000 on your computer, so you can't run this server. What you should do is look for other processes running, and kill them, then re-try.
For instance, if you're on Mac, you open the activity monitor, look for node apps, and kill them.
This will fix your issue!
UPDATE: Look at your package.json if you want to see what the npm start script is doing.