I am having a bit of a hard time getting back to a Node.js project after a while.
I need to implement some new feature and things have changed since I previously worked on that same project.
Here is one error I get in the logs:
2020-02-17T16:42:42.602361+00:00 app[web.1]: Error: Most middleware (like json) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
2020-02-17T16:42:42.602363+00:00 app[web.1]: at Function.get (/app/node_modules/express/lib/express.js:89:13)
2020-02-17T16:42:42.602365+00:00 app[web.1]: at Object.<anonymous> (/app/index.js:57:17)
..........
After reading the net looking for a solution, I added this line to the dependencies section of my package.json file:
"body-parser": "*",
And then to my index.js file I added the following line:
var bodyParser = require('body-parser');
and replaced those two lines:
app.use(express.json());
app.use(express.urlencoded());
by these:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
It did not solve the problem, so I must be doing something wrong or not be doing all what is needed.
I am no expert in Node.js and am certainly not sure that I correctly used what I may have found on the net. So if someone had relevant advice, that would be more that welcome.
For reference, here is the current package.json file:
{
"name": "parse-server-example",
"version": "1.4.0",
"description": "An example Parse API server using the parse-server module",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/ParsePlatform/parse-server-example"
},
"license": "MIT",
"dependencies": {
"#parse/simple-mailgun-adapter": "^1.0.3",
"ejs": "^3.0.1",
"express": "^4.17.1",
"body-parser": "1.19.0",
"kerberos": "~0.0.x",
"parse": "~1.8.0",
"parse-server": "*"
},
"scripts": {
"start": "node index.js"
},
"engines": {
"node": ">=4.3"
}
}
And this is the relevant contents of the index.js file:
var express = require('express');
var bodyParser = require('body-parser');
var ParseServer = require('parse-server').ParseServer;
var path = require('path');
var mongo = require('mongodb');
var theMgoClient = mongo.MongoClient;
var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
if (!databaseUri) {
console.log('DATABASE_URI not specified, falling back to localhost.');
}
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
// views is the directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
var api = new ParseServer({
databaseURI: databaseUri,
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID,
masterKey: process.env.MASTER_KEY,
serverURL: "https://myworld.herokuapp.com/parse",
publicServerURL: 'https://myworld.herokuapp.com/parse',
appName: 'MyGoodApp',
liveQuery: {
classNames: ["MyThings_List"]
},
verifyUserEmails: true,
emailAdapter: {
module: '#parse/simple-mailgun-adapter',
options: {
fromAddress: 'contact868#hmail.com',
domain: 'mydomain.pet',
apiKey: process.env.EML_ADAPTER_KEY
}
}
});
// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
// Serve the Parse API on the /parse URL prefix
var mountPath = process.env.PARSE_MOUNT;
app.use(mountPath, api);
// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
displayFunc("index", res);
});
app.get('/option1', function(req, res) {
......
});
app.get('/option2', function(req, res) {
......
});
app.get('/option3', function(req, res) {
......
});
app.post('/newStuff', function(req, res) {
......
});
Now, here is what I get when running npm install:
ShellPrompt$ npm install
> bcrypt#1.0.2 install /Users/me/Documents/Heroku/myapp/node_modules/parse-server/node_modules/bcrypt
> node-pre-gyp install --fallback-to-build
node-pre-gyp ERR! Tried to download(404): https://github.com/kelektiv/node.bcrypt.js/releases/download/v1.0.2/bcrypt_lib-v1.0.2-node-v72-darwin-x64.tar.gz
node-pre-gyp ERR! Pre-built binaries not found for bcrypt#1.0.2 and node#12.16.0 (node-v72 ABI) (falling back to source compile with node-gyp)
node-pre-gyp ERR! Tried to download(undefined): https://github.com/kelektiv/node.bcrypt.js/releases/download/v1.0.2/bcrypt_lib-v1.0.2-node-v72-darwin-x64.tar.gz
node-pre-gyp ERR! Pre-built binaries not found for bcrypt#1.0.2 and node#12.16.0 (node-v72 ABI) (falling back to source compile with node-gyp)
CXX(target) Release/obj.target/bcrypt_lib/src/blowfish.o
CXX(target) Release/obj.target/bcrypt_lib/src/blowfish.o
CXX(target) Release/obj.target/bcrypt_lib/src/bcrypt.o
sed: ./Release/.deps/Release/obj.target/bcrypt_lib/src/blowfish.o.d.raw: No such file or directory
make: *** [Release/obj.target/bcrypt_lib/src/blowfish.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:194:23)
gyp ERR! stack at ChildProcess.emit (events.js:321:20)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
Related
Im doing migration to parse server. And until now everything worked well. But now I want to add google cloud storage file adapter and if I add this line to my code it stops working. Can you somebody tell me why.
var GCSAdapter = require('parse-server-gcs-adapter');
This is the log:
npm ERR! Linux 3.13.0-105-generic
npm ERR! argv "/app/.heroku/node/bin/node" "/app/.heroku/node/bin/npm" "start"
npm ERR! node v6.9.1
npm ERR! npm v3.10.8
npm ERR! code ELIFECYCLE
npm ERR! parse-server-example#1.4.0 start: `node index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the parse-server-example#1.4.0 start script 'node index.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the parse-server-example package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node index.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs parse-server-example
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls parse-server-example
npm ERR! There is likely additional logging output above.
2017-01-29T16:56:58.161879+00:00 app[web.1]:
npm ERR! Please include the following file with any support request:
npm ERR! /app/npm-debug.log
My index.js file:
// Example express application adding the parse-server module to expose Parse
// compatible API routes.
var express = require('express');
var ParseDashboard = require('parse-dashboard');
var ParseServer = require('parse-server').ParseServer;
var GCSAdapter = require('parse-server-gcs-adapter');
var path = require('path');
var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
if (!databaseUri) {
console.log('DATABASE_URI not specified, falling back to localhost.');
}
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'myAppId',
masterKey: process.env.MASTER_KEY || '', //Add your master key here. Keep it secret!
serverURL: process.env.SERVER_URL || 'http://localhost:1337/parse', // Don't forget to change to https if needed
// liveQuery: {
// classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions
// }
// filesAdapter: new GCSAdapter(
// "oval-proxy-117311",
// "./SymboloKey",
// "Symbolo",
// {directAccess: true}
// )
});
// Client-keys like the javascript key or the .NET key are not necessary with parse-server
// If you wish you require them, you can set them as options in the initialization above:
// javascriptKey, restAPIKey, dotNetKey, clientKey
const dashboard = new ParseDashboard( {
'allowInsecureHTTP': true,
'apps': [
{
'serverURL': process.env.SERVER_URL,
'appName': 'Symbolo',
'appId': process.env.APP_ID,
'masterKey': process.env.MASTER_KEY
}
],
'users': [
{
'user': 'public',
'pass': 'qwerty'
}
]
}, true )
var app = express();
// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));
// Serve the Parse API on the /parse URL prefix
var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);
// serve the Parse Dashboard
app.use('/dashboard', dashboard)
// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
res.status(200).send('I dream of being a website. Please star the parse-server repo on GitHub!');
});
// There will be a test page available on the /test path of your server url
// Remove this before launching your app
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname, '/public/test.html'));
});
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
// This will enable the Live Query real-time server
// ParseServer.createLiveQueryServer(httpServer);
If I run npm install:
Klemens-MBP-2:Cloud klemen$ npm install
npm WARN deprecated mongodb#2.2.10: Please upgrade to 2.2.19 or higher
> bcrypt#1.0.2 install /Users/klemen/Dev/Newcomm/Cloud/node_modules/bcrypt
> node-pre-gyp install --fallback-to-build
node-pre-gyp ERR! Tried to download(404): https://github.com/kelektiv/node.bcrypt.js/releases/download/v1.0.2/bcrypt_lib-v1.0.2-node-v51-darwin-x64.tar.gz
node-pre-gyp ERR! Pre-built binaries not found for bcrypt#1.0.2 and node#7.4.0 (node-v51 ABI) (falling back to source compile with node-gyp)
Before I start explaining my error, let me say I'm a Windows user and don't have a lot of experience using Unix commands. So each of these steps are done using the Docker Quickstart Terminal (MINGW64).
It was a few weeks ago I first heard about docker and thought using it for a node/express website. So I installed the Docker package on my Synology server.
After finishing up the website I've done the following:
I followed the instructions on this website:
https://docs.docker.com/windows/step_one/ Up until the last step,
everything worked (including docker run hello-world)
Then it was onto "Dockerizing a Node.js web app":
https://docs.docker.com/engine/examples/nodejs_web_app/
File hierarchy:
src (C:.....\projectname)
--assets (folder)
--controllers (folder)
--public (folder)
--src (folder)
--util (folder)
--views (folder)
--node_modules (folder)
--bin (folder)
----www (file, no extention)
--app.js (file)
--Dockerfile (file, no extention)
--package.json (file)
As for content:
www:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('projectname:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
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 app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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(require('./controllers'));
};
// 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;
package.json:
{
"name": "projectname",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"bcrypt-nodejs": "0.0.3",
"body-parser": "~1.13.2",
"bookshelf": "^0.9.2",
"cookie-parser": "~1.3.5",
"debug": "~2.2.0",
"express": "~4.13.1",
"express-session": "^1.13.0",
"i18n": "^0.8.0",
"jade": "~1.11.0",
"knex": "^0.10.0",
"morgan": "~1.6.1",
"mysql": "^2.10.2",
"passport": "^0.3.2",
"passport-local": "^1.0.0",
"serve-favicon": "~2.3.0"
},
"devDependencies": {
"autoprefixer": "^6.3.3",
"browserify": "^13.0.0",
"connect-livereload": "^0.5.4",
"grunt": "^0.4.5",
"grunt-browserify": "^4.0.1",
"grunt-contrib-cssmin": "^0.14.0",
"grunt-contrib-sass": "^0.9.2",
"grunt-contrib-uglify": "^0.11.1",
"grunt-contrib-watch": "^0.6.1",
"grunt-postcss": "^0.7.2"
}
}
So as you can see in the package.json and www (which was generated by the express generator command), I have to write npm start to run the node/express server.
Dockerfile:
FROM centos:centos6
RUN yum install -y epel-release
RUN yum install -y nodejs npm
COPY package.json /projectname/package.json
RUN cd /projectname; npm install --production
COPY . /projectname
EXPOSE 8080
CMD ["npm", "start"]
After a successful build docker build -t username/projectname . I do get a SECURITY WARNING:
Successfully built 5ed562273b56
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.
Apart from that no errors are thrown, so I ran the image: docker run -p 49160:8080 -d username/projectname. After which I get a long hash string
de297db51ab6fb3f842abb58267c1e189d2b9de51715a619a2f5431e868dc54f
Still following the principles on https://docs.docker.com/engine/examples/nodejs_web_app/. To test the image I listed the container id using docker ps which got me this:
CONTAINER ID | IMAGE | COMMAND | CREATED | STATUS | PORTS | NAMES
So completely empty! Nothing, except for the headers of the table... But when I use the code provided in the link and build their image it does give me a result (as stated in the article):
CONTAINER ID | IMAGE | COMMAND | CREATED | STATUS | PORTS | NAMES
26d3ac309d81 | username/centos-node-testing | "node /src/index.js" | 35 minutes ago | Up 35 minutes | 0.0.0.0:49160->8080/tcp | gigantic_ritchie
Just to be sure, I tried calling the app using the curl-command: curl -i 192.168.99.100:49160. Unfortunately that gave me an error:
curl: (7) Failed to connect to 192.168.99.100 port 49160: Connection refused
The ip address is retrieved using the docker-machine ip command.
As a last resort, someone suggested to simply run the app using following command docker run username/projectname. That however gave me an error:
npm ERR! Error: ENOENT, open '/package.json'
npm ERR! If you need help, you may report this log at:
npm ERR! http://github.com/isaacs/npm/issues
npm ERR! or email it to:
npm ERR!
npm ERR! System Linux 4.1.19-boot2docker
npm ERR! command "node" "/usr/bin/npm" "start"
npm ERR! cwd /
npm ERR! node -v v0.10.42
npm ERR! npm -v 1.3.6
npm ERR! path /package.json
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /npm-debug.log
npm ERR! not ok code 0
Any ideas what might cause this?
Your container is non-existent because the command you've provided (CMD, above) is returning a non-zero exit status, and the container is destroyed due to failure. In your Dockerfile, let's please try something like the following, which should ensure that npm start is run from within your project root:
FROM centos:centos6
RUN yum install -y epel-release
RUN yum install -y nodejs npm
COPY package.json /projectname/package.json
# Set the working directory
WORKDIR /projectname
RUN npm install --production
COPY . /projectname
EXPOSE 8080
CMD ["npm", "start"]
Also, for future, you might have luck troubleshooting a container if you use docker run -it username/projectname /bin/bash.
getting this error while running the command npm start
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli 'start' ]
2 info using npm#3.3.12
3 info using node#v5.4.1
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle passport-local#0.0.0~prestart: passport-local#0.0.0
6 silly lifecycle passport-local#0.0.0~prestart: no script for prestart, continuing
7 info lifecycle passport-local#0.0.0~start: passport-local#0.0.0
8 verbose lifecycle passport-local#0.0.0~start: unsafe-perm in lifecycle true
9 verbose lifecycle passport-local#0.0.0~start: PATH: C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin;C:\Users\Rohil\Documents\ddbproject\passport-local\node_modules\.bin;C:\Users\Rohil\bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\local\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\bin;C:\Users\Rohil\bin;C:\oraclexe\app\oracle\product\11.2.0\server\bin;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client;C:\Program Files\Intel\iCLS Client;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\WiFi\bin;C:\Program Files\Common Files\Intel\WirelessCommon;C:\Program Files\Java\jdk1.8.0_45\bin;C:\Program Files\nodejs;C:\mongodb\bin;C:\Users\Rohil\AppData\Local\Programs\Python\Python35-32;C:\Program Files\MongoDB\Server\3.2\bin;C:\Users\Rohil\AppData\Roaming\npm;C:\Program Files\MongoDB\Server\3.2\bin;C:\Program Files\Git\usr\bin\vendor_perl;C:\Program Files\Git\usr\bin\core_perl
10 verbose lifecycle passport-local#0.0.0~start: CWD: C:\Users\Rohil\Documents\ddbproject\passport-local
11 silly lifecycle passport-local#0.0.0~start: Args: [ '/d /s /c', 'node ./bin/www' ]
12 silly lifecycle passport-local#0.0.0~start: Returned: code: 1 signal: null
13 info lifecycle passport-local#0.0.0~start: Failed to exec start script
14 verbose stack Error: passport-local#0.0.0 start: `node ./bin/www`
14 verbose stack Exit status 1
14 verbose stack at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\lib\utils\lifecycle.js:232:16)
14 verbose stack at emitTwo (events.js:87:13)
14 verbose stack at EventEmitter.emit (events.js:172:7)
14 verbose stack at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\lib\utils\spawn.js:24:14)
14 verbose stack at emitTwo (events.js:87:13)
14 verbose stack at ChildProcess.emit (events.js:172:7)
14 verbose stack at maybeClose (internal/child_process.js:821:16)
14 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
15 verbose pkgid passport-local#0.0.0
16 verbose cwd C:\Users\Rohil\Documents\ddbproject\passport-local
17 error Windows_NT 10.0.10586
18 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
19 error node v5.4.1
20 error npm v3.3.12
21 error code ELIFECYCLE
22 error passport-local#0.0.0 start: `node ./bin/www`
22 error Exit status 1
23 error Failed at the passport-local#0.0.0 start script 'node ./bin/www'.
23 error Make sure you have the latest version of node.js and npm installed.
23 error If you do, this is most likely a problem with the passport-local package,
23 error not with npm itself.
23 error Tell the author that this fails on your system:
23 error node ./bin/www
23 error You can get their info via:
23 error npm owner ls passport-local
23 error There is likely additional logging output above.
24 verbose exit [ 1, true ]
tried installing node-gyp
and also cleaning cache, node_modules and running a fresh npm start
even then, i get an error saying module.js:327: throw err;
cannot find module 'mongodb/node_modules/bson'
my package.json file:
{
"name": "passport-local",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "^1.13.2",
"chai": "~1.8.1",
"cookie-parser": "^1.3.5",
"express": "^4.13.1",
"express-session": "^1.10.1",
"jade": "^1.11.0",
"mocha": "~1.14.0",
"mongoose": "^3.8.22",
"morgan": "^1.6.1",
"passport": "^0.2.1",
"passport-local": "^1.0.0",
"passport-local-mongoose": "^1.0.0",
"should": "~2.1.0",
"serve-favicon": "^2.2.0",
"debug": "^2.1.1"
}
}
after running the command npm link mongodb and then running npm start, im getting a new error:
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
events.js:141
throw er; // Unhandled 'error' event
^
Error: failed to connect to [localhost:27017]
at null.<anonymous> (C:\Users\Rohil\Documents\ddbproject\passport-local\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\server.js:556:25)
at emitThree (events.js:97:13)
at emit (events.js:175:7)
at null.<anonymous> (C:\Users\Rohil\Documents\ddbproject\passport-local\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\connection_pool.js:156:15)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at Socket.<anonymous> (C:\Users\Rohil\Documents\ddbproject\passport-local\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\connection.js:534:10)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at emitErrorNT (net.js:1255:8)
at nextTickCallbackWith2Args (node.js:474:9)
at process._tickCallback (node.js:388:17)
npm ERR! Windows_NT 10.0.10586
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v5.4.1
npm ERR! npm v3.3.12
npm ERR! code ELIFECYCLE
npm ERR! passport-local#0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the passport-local#0.0.0 start script 'node ./bin/www'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the passport-local package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node ./bin/www
npm ERR! You can get their info via:
npm ERR! npm owner ls passport-local
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! C:\Users\Rohil\Documents\ddbproject\passport-local\npm-debug.log
the contents of the ./bin/www file are:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('passport-local:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
This issue started after editing my app.js file:
// dependencies
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 mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
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(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('express-session')({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// passport config
var Account = require('./models/account');
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());
// mongoose
mongoose.connect('mongodb://localhost/passport_local_mongoose_express4');
// 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;
also created a new file /models/account.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var Account = new Schema({
username: String,
password: String
});
Account.plugin(passportLocalMongoose);
module.exports = mongoose.model('Account', Account);
any errors in that?
mongo refuses to start too
$ mongo
MongoDB shell version: 3.2.1
connecting to: test
2016-02-20T23:34:10.083+0530 W NETWORK [thread1] Failed to connect to 127.0.0.1:27017, reason: errno:10061 No connection could be made because the target machine actively refused it.
2016-02-20T23:34:10.084+0530 E QUERY [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect#src/mongo/shell/mongo.js:224:14
#(connect):1:6
exception: connect failed
The mongoose error might be due to unstable version of mongoose, update "mongoose": "3.8" in package.json. (Followed by npm install) This might remove mongoose warning.
Check this link for
Failed to load c++ extension
Made sure these two packages are at these versions
"mongodb": "^2.1.16",
"mongoose": "^4.4.12"
And running the below commands with reference to here
npm install node-gyp -g
npm cache clean
rm -rf node_modules
npm install
I've installed express.js in specificed folder scoreboard, I'm trying to execute "npm start" in CLI, then I got error was:
0 info it worked if it ends with ok
1 verbose cli [ 'node', '/opt/rh/nodejs010/root/usr/bin/npm', 'start' ]
2 info using npm#1.3.24
3 info using node#v0.10.25
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info prestart application-name#0.0.1
6 info start application-name#0.0.1
7 verbose unsafe-perm in lifecycle true
8 info application-name#0.0.1 Failed to exec start script
9 error application-name#0.0.1 start: `node app.js`
9 error Exit status 8
10 error Failed at the application-name#0.0.1 start script.
10 error This is most likely a problem with the application-name package,
10 error not with npm itself.
10 error Tell the author that this fails on your system:
10 error node app.js
10 error You can get their info via:
10 error npm owner ls application-name
10 error There is likely additional logging output above.
11 error System Linux 2.6.32-504.3.3.el6.x86_64
12 error command "node" "/opt/rh/nodejs010/root/usr/bin/npm" "start"
13 error cwd /var/lib/openshift/54d99b5f5973ca0a11000120/app-root/runtime/repo/Scoreboard/scoreboard
14 error node -v v0.10.25
15 error npm -v 1.3.24
16 error code ELIFECYCLE
17 verbose exit [ 1, true ]
There content of app.js is:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
// all environments
//app.set('port', process.env.PORT || 3000);
app.set('port', process.env.OPENSHIFT_NODEJS_PORT || 8080);
app.set('ipaddr', process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1");
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
I had no idea how to fix it, I'm looking a solution how to run express in Openshift, Thanks!
I know it's been a long time since this issue was opened, but I could deploy it successfully to Openshift.
Like Thimoty Gu said, there were some problems in your app.js. because some features you are using from Express are deprecated, what can impact to deploy an app to Openshift.
In Openshift I've had problems with very simple things, like setting the package.json with * instead of the right version of the dependency I wanted.
I did a few changes in your code without the routes file and it worked in my test. Basically, the result is:
package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies" : {
"express" : "4.9.5" //it's important to set a version, instead of using *
}
}
server.js
/**
* Module dependencies.
*/
var express = require('express')
//, routes = require('./routes')
//, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
// all environments
//app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
//app.use(express.favicon());
//app.use(express.logger('dev'));
//app.use(express.bodyParser());
//app.use(express.methodOverride());
//app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
//if ('development' == app.get('env')) {
// app.use(express.errorHandler());
//}
app.get('/', function(req, res, err) {
res.send("You have accessed page / (root)");
});
app.get('/users', function(req, res, err) {
res.send("You have accessed page /users (users)");
});
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var address = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
console.log("Port: " + port);
console.log("Address: " + address);
var server = app.listen(port, address, function() {
console.log('Express server listening on port ' + port);
});
In summary, I just removed/commented your libraries that are not supported or are deprecated in Express. To use them now, you should include them from the new libraries that support them.
Hope it's somehow useful, even so long later.
This is common SO question but didn't get the solution. So I am again putting it here.
Here is app.js
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
require('./routes/sockets.js').initialize(server);
here is sockets.js inside routes folder
var io = require('socket.io');
exports.initialize = function(server) {console.log('init called');
io = io.listen(server);console.log('io');
io.sockets.on("connection", function(socket){console.log("connected");
socket.send(JSON.stringify({type:'serverMessage',message: 'Welcome to the most interesting chat room on earth!'}));
socket.on('message', function(message){
message= JSON.parse(message);
if(message.type == "userMessage")
{
socket.broadcast.send(JSON.stringify(message));
message.type = "myMessage";
socket.send(JSON.stringify(message));
}
});
});
};
Inside sockets.js console.log('init called'); console.log('io'); is printing well. When i run this app using npm start is got following error:
npm WARN package.json application-name#0.0.1 No repository field.
npm WARN package.json application-name#0.0.1 No readme data.
> application-name#0.0.1 start D:\Applications\New folder\node\chat
> node app.js
init called
info - socket.io started
io
Express server listening on port 3000
GET / 200 312ms - 511
http.js:707
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:707:11)
at ServerResponse.res.setHeader (D:\Applications\New folder\node\chat\node_m
odules\express\node_modules\connect\lib\patch.js:59:22)
at next (D:\Applications\New folder\node\chat\node_modules\express\node_modu
les\connect\lib\proto.js:153:13)
at Function.app.handle (D:\Applications\New folder\node\chat\node_modules\ex
press\node_modules\connect\lib\proto.js:198:3)
at Server.app (D:\Applications\New folder\node\chat\node_modules\express\nod
e_modules\connect\lib\connect.js:66:31)
at Manager.handleRequest (D:\Applications\New folder\node\chat\node_modules\
socket.io\lib\manager.js:564:28)
at Server.<anonymous> (D:\Applications\New folder\node\chat\node_modules\soc
ket.io\lib\manager.js:118:10)
at Server.EventEmitter.emit (events.js:117:20)
at HTTPParser.parser.onIncoming (http.js:2051:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:122:23
)
When i access localhost:3000 in browser all it happens. I am using node version v0.10.10, express 3.4.4.
Got the solution!! It was because of some version mismatch. Here is the dependency that i used
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.4.4",
"socket.io": "0.9",
"jade": "*"
}
}