Hello World Node.js/Express application error - node.js

I am learning MEAN stack so started with Node.js and Express first. I run Nginx on Windows 10. I installed the latest Node. NPM version is 3.10.3, Node version is 6.7.0, and Express version is 4.14.0. I did npm install express --save, npm install mongoose --save, npm install body-parser --save, and created the server.js file. I did node server on my sources and I got the following error:
C:\nginx\html>node server
C:\nginx\html\server.js:7
app.get('/', function(req, res){
^
TypeError: app.get is not a function
at Object. (C:\nginx\html\server.js:7:5)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.runMain (module.js:590:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
C:\nginx\html>
And the code in my server.js file is:
var express = require('express');
var express = require('mongoose');
var express = require('body-parser');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(80);
I am not sure how a hello world application can go wrong. I saw a lot of tuts and code with the same thing but working for them. Even the Express's official hello world app has same code.

try this
var express = require('express');
var mongoose= require('mongoose');
var bodyparser = require('body-parser');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(80);

You need to install express not expression as following
npm install express --save
and then you like play
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.get('/', function(req, res){
res.send('hello world');
});
app.post('/', function(req, res){
res.json({data: req.body});
});
app.listen(3000);
and then try to listen another port that is above 1024 may be 3000 or 8080 or anything else otherwise you have to run cmd as Administrator

Related

Module not found error - NodeJS Express.JS

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);

Mongoose is undefined error

First time i have tried out to create a simple mean application.
I have followed the steps as per the below link
https://scotch.io/tutorials/setting-up-a-mean-stack-single-page-application#starting-our-node-application-packagejson
Finally i am getting the errors as
ReferenceError: mongoose is not defined
at Object.<anonymous> (C:\Users\Myname\Desktop\Mean sample\server.js:19:2)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
server.js
// modules =================================================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
// configuration ===========================================
// config files
var db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to our mongoDB database
// (uncomment after you enter in your own credentials in config/db.js)
mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);
// shoutout to the user
console.log('Magic happens on port ' + port);
// expose app
exports = module.exports = app;
How to fix it?
Can anyone please explain the steps to clear this issue
install mongoose
npm i mongoose --save
then import in your server.js file
var express = require('express');
var mongoose = require('mongoose') // import it
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

Azure hosted node app cannot find module 'async/each'

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.

Trying to deploy app on openshift. "program node app.js exited with code 8". Can't figure out what's going on

I'm pretty new at this. This is my first time trying to deploy an app in a production environment. It works totally fine locally (and of course with local environment variables instead of Openshift's environment variables). But on openshift I just can't get it to run. It always responds with "503 Service Temporarily unavailable". I've been tinkering with it for hours, and looking everywhere for a solution, but nothing is working.
Here's what I have in my index.js file (it's just a simple mongodb utilizing to-do list. And like I said, it works fine locally, but yes, it's very messy. Like I said. I'm new):
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectId;
var methodOverride = require('method-override');
var session = require('express-session');
var app = express();
var router = express.Router();
var dbUrl = 'mongodb://$OPENSHIFT_MONGODB_DB_HOST:$OPENSHIFT_MONGODB_DB_PORT/todo_list';
var result;
var list;
var port = process.env.OPENSHIFT_NODEJS_PORT;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(methodOverride(function(req, res){
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
// look in urlencoded POST bodies and delete it
var method = req.body._method
delete req.body._method
return method
}
}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
function updateList(res){
MongoClient.connect(dbUrl, function(err, db){
if(err){console.log(err);}
var list = db.collection('list');
list.find({}).toArray(function(err, docs){
res.render('index', { title: 'To do:', list: docs });
});
});
};
//routes
app.get('/', function(req, res){
updateList(res);
});
app.post('/', function(req, res){
var data = req.body.words;
MongoClient.connect(dbUrl, function(err, db){
var list = db.collection('list');
list.insert({ task: data }, updateList(res));
});
});
app.delete('/:id', function(req, res){
var removal = req.params.id;
MongoClient.connect(dbUrl, function(err, db){
var list = db.collection('list');
list.remove({ _id: ObjectId(removal)}, updateList(res));
});
res.redirect('/');
});
var server = app.listen(port, function(){
console.log('listening');
});
module.exports = server;
And then here's what's logged out to me:
Error: listen EACCES
at errnoException (net.js:901:11)
at Server._listen2 (net.js:1020:19)
at listen (net.js:1061:10)
at Server.listen (net.js:1135:5)
at EventEmitter.listen (/var/lib/openshift/<key>/app-root/runtime/repo/node_modules/express/lib/application.js:617:24)
at Object.<anonymous> (/var/lib/openshift/<key>/app-root/runtime/repo/index.js:66: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)
DEBUG: Program node index.js exited with code 8
DEBUG: Starting child process with 'node index.js'
I'm at a loss. Please help.
You also need to bind to the OPENSHIFT_NODEJS_IP environment variable. This can be done in the second argument of app.listen, like as follows:
var ipAddress = process.env.OPENSHIFT_NODEJS_IP
var server = app.listen(port, ipAddress, function(){
console.log('listening');
});
If you don't do this, the default IP address will be 0.0.0.0 which won't work on Openshift

Using stylus middleware with express 4, SyntaxError

Im trying to use nodejs express v4 with stylus, but its throwing SyntaxError. Please help, also you can find my server.js below;;
Please note: Im first time creating MEANstack project, and dont be harsh on me :)
Your environment has been set up for using Node.js 0.10.26 (x64) and npm.
Error: Most middleware (like logger) is no longer bundled with Express and must
be installed separately. Please see https://github.com/senchalabs/connect#middle
ware.
at Function.Object.defineProperty.get (C:\Sites\meanProject\node_modules\exp
ress\lib\express.js:89:13)
at Object.<anonymous> (C:\Sites\meanProject\server.js:10:17)
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)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
server.js:
var express = require('express');
var stylus = require('stylus');
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
//set view engine
app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
//style middlware
app.use(stylus.middleware({
src: __dirname + '/public',
dest: __dirname + '/public/css',
compile: function compile(str, path){
return stylus(str).set('filename', path).set('compress', true);
}
}));
app.use(express.static(path.join(__dirname + '/public')));//all public req will be responded by public dir now.
//load route
app.get('*', function(req, res){
res.render('index');
});
//start listening on server
var port = 3000;
app.listen(port);
console.log('Server running at localhost:' + port);
#thyforhtian yes, you were right my code was outdated.
I fixed it.
Im not using nodejs to compile my stylus file anymore, instead im using gulp.
Posting my file here, with steps, it might be helpful for someone-else.
Compile stylus files with gulp watch. And code for express server js file
Started with installing node modules
npm init
npm install -save express jade
// Step 1: Install gulp globally
npm install -g gulp
// Step 2: Install gulp in your project
npm install --save-dev gulp gulp-stylus gulp-plumber
npm install morgan body-parser --save
server.js
var express = require('express');
var stylus = require('stylus');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var app = express();
//set view engine
app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.urlencoded());
app.use(cookieParser());
//all public req will be responded by public dir now.
app.use(express.static(__dirname + '/public'));
//load route
app.get('*', function(req, res){
res.render('index');
});
//start listening on server
var port = 3000;
app.listen(port);
console.log('Server running at localhost:' + port);
gulpfile.js
var gulp = require('gulp');
var stylus = require('gulp-stylus');
var plumber = require('gulp-plumber');
gulp.task('stylus', function() {
gulp.src('public/stylesheets/style.styl')
.pipe(plumber())
.pipe(stylus())
.pipe(gulp.dest('public/stylesheets'));
});
gulp.task('watch', function() {
gulp.watch('public/stylesheets/*.styl', ['stylus']);
});
gulp.task('default', ['stylus', 'watch']);
run gulp to execute
There seem to be a comma missing after src: __dirname + '/public'.
UPDATE
You should require and use it like this (first add it to package.json and npm install):
var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
app.use(logger('dev'));
app.use(bodyParser());

Resources