Heroku Node.js - Permission Denied - node.js

I am trying to deploy a simple application to Heroku which makes use of the modules 'socket.io' and 'connect'. When I deploy the application I get a Permission Denied error and the application crashes. I am getting the port number from the environment property 'PORT'. I am configuring socket.io to use long polling rather than WebSockets (as I know they are not supported).
Can someone tell me what I'm doing wrong?
var io = require('socket.io'),
connect = require('connect');
var port = process.env.PORT || 5000;
var app = connect().use(connect.static('public')).listen(port);
var chat_room = io.listen(app);
chat_room.configure(function () {
chat_room.set("transports", ["xhr-polling"]);
chat_room.set("polling duration", 10);
});
chat_room.sockets.on('connection', function(socket){
socket.emit('entrance', {message:'Welcome to the chat room.'});
socket.on('disconnect', function(){
chat_room.sockets.emit('exit', {message:'A chatter has disconnected.'});
});
socket.on('chat', function(data){
chat_room.sockets.emit('chat',{message: '# ' + data.message});
});
chat_room.sockets.emit('entrance', {message: 'A new chatter is online.'});
});
Here is the error from the log:
2013-02-01T04:24:04+00:00 app[web.1]: Error: EACCES, Permission denied
2013-02-01T04:24:04+00:00 app[web.1]: at Server.listen (net.js:1063:20)
2013-02-01T04:24:04+00:00 app[web.1]: node.js:134
2013-02-01T04:24:04+00:00 app[web.1]: at Server._doListen (net.js:1098:5)
2013-02-01T04:24:04+00:00 app[web.1]: at net.js:1069:14
2013-02-01T04:24:04+00:00 app[web.1]: at Object.lookup (dns.js:153:45)
2013-02-01T04:24:04+00:00 app[web.1]: at Object.listen (/app/node_modules/socket.io/lib/socket.io.js:67:12)
2013-02-01T04:24:04+00:00 app[web.1]: at Object.<anonymous> (/app/main.js:8:20)
2013-02-01T04:24:04+00:00 app[web.1]: at Module.load (module.js:336:31)
2013-02-01T04:24:04+00:00 app[web.1]: at Module._compile (module.js:404:26)
2013-02-01T04:24:04+00:00 app[web.1]: at Function._load (module.js:297:12)
2013-02-01T04:24:04+00:00 app[web.1]: at Object..js (module.js:410:10)
2013-02-01T04:24:06+00:00 heroku[web.1]: Process exited with status 1
2013-02-01T04:24:06+00:00 heroku[web.1]: State changed from starting to crashed
Thanks!

Related

I'm not able to start the mongo db server, getting the following error: [nodemon] app crashed - waiting for file changes before starting

This is server.js and .env file
I'm trying to start the server but it is throwing an error.
server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true });
const connection = mongoose.connection;
connection.once('open',() => {
console.log("MongoDB database connection established successfully");
})
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
})
.env
ATLAS_URI = mongodb+srv://rnvsri:vastav123#cluster0.dgnw1.mongodb.net/test?retryWrites=true&w=majority
Issue:
In cmd, I'm giving the command nodemon server.js
but the server is not starting and it is throwing the following error.
nodemon] app crashed - waiting for file changes before starting...
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
node:events:368
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::5000
at Server.setupListenHandle [as _listen2] (node:net:1334:16)
at listenInCluster (node:net:1382:12)
at Server.listen (node:net:1469:7)
at Function.listen (/Users/rnvsrivastava/mern/restaurant-reviews/backend/backend/node_modules/express/lib/application.js:618:24)
at Object.<anonymous> (/Users/rnvsrivastava/mern/restaurant-reviews/backend/backend/server.js:20:6)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1361:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EADDRINUSE',
errno: -48,
syscall: 'listen',
address: '::',
port: 5000
}
[nodemon] app crashed - waiting for file changes before starting...
Can someone help?
port you are using is used by another process you can find it by
command
lsof -i :PORT and can kill using kill command
kill PID

How to resolve "unspecified name" error of postman when running URL of Heroku | NodeJs | MongoDB

I am new to Heroku, NodeJS and MongoDB. I created a login form in flutter and its backend is in NodeJS and MongoDB. I used Heroku for connecting backend to flutter, but when I run the URL (which is given by Heroku at the time of building project) on postman it gives me "unspecified name"
here is code of my app.js
var body = require('body-parser');
const mongoose = require('mongoose');
var mongodb = require('mongodb')
var url = 'mongodb://localhost:27017/Mongodb'
var express = require('express');
var app = express();
app.use(body.json());
var bcrypt = require('bcrypt');
var CryptoJS = require("crypto-js")
var jwt = require('jsonwebtoken');
const router= express.Router()
const User = require('./connection');
mongoose.connect('mongodb://localhost:27017/Mongodb', { useUnifiedTopology: true, useNewUrlParser: true },function(err){
if(err){
console.log(err)
}else{
console.log("connection Successful")
}
})
// router.get('/Dashboard', (req, res) => {
// res.send('Hello World')
// })
function checkToken(req,res,result){
const header= req.headers.token;
if(typeof header !== 'undefined'){
const bearer =header.split('.');
const token = bearer[1]
//console.log(token)
req.token = token
//next();
result();
}else
res.json("Error")
}
const login = require('./routes/login')
app.post("/login", async (req, res, next) => {
console.log("login api hit")
login(req,res,next)
} )
const userDashboard = require('./routes/userdashboard')
app.post("/Dashboard",checkToken,(req,res)=> {
userDashboard(req,res);
})
const PORT = process.env.PORT || 5000
app.listen(PORT, function(){
console.log("Server is running")
})
here is the code for ./routes/login
var body = require('body-parser');
const mongoose = require('mongoose');
var mongodb = require('mongodb')
var url = 'mongodb://localhost:27017/Mongodb'
var express = require('express');
var app = express();
app.use(body.json());
const User = require('../connection');
var bcrypt = require('bcrypt');
var CryptoJS = require("crypto-js")
var jwt = require('jsonwebtoken');
login=(req,res,next)=>{
console.log(req.data)
User.find({"username":req.body.username},function(err,data){
if(err){
console.log("unspecified name")
res.status(400).json("unspecified name")
return;
}
else{
console.log(data.length)
if(data.length<=0)
{
res.status(300).json({
"message":"Invalid Input!"
})
}
else {
//bcrypt.compare(req.body.password,data[0].password).then(function(result) {
var bytes = CryptoJS.AES.decrypt(data[0].password, 'my-secret-key#123');
var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
console.log(decryptedData)
if (req.body.password==decryptedData)
{
login = "Succesful";
var token = jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: "2 minute"})
res.status(200).json({auth: true, AccessToken:token, User:data[0]})
}
else
{res.status(300).json({
"message":"Input!"
})}
// });
}}
})
}
module.exports = login;
here is the snap which shows "login api hit"
here is the snap which shows "Server is running"
and here is the 404 error annd 400 error
and here is the postman snap
Now let me know please is my server is running properly? it seems it is! but why it's showing "unspecified name" on postman?
kindly please help I'm new in this stuff, any help will be appreciated!
Thank you!
---------------------------EDITED POST---------------------------------------
my database data is look like this
but cmd screen shows this
can anyone tell me what is logic behind this? from where these came?
------------------------EDITED POST---------------------------------------------
This is the output when I enter the credentials!
and here it is ouput of cmd
2021-05-25T11:04:30.507933+00:00 app[web.1]: Server is running
2021-05-25T11:04:30.682233+00:00 heroku[web.1]: State changed from starting to up
2021-05-25T11:05:00.561298+00:00 app[web.1]: MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
2021-05-25T11:05:00.561320+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:832:32)
2021-05-25T11:05:00.561321+00:00 app[web.1]: at /app/node_modules/mongoose/lib/index.js:345:10
2021-05-25T11:05:00.561335+00:00 app[web.1]: at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:9:12)
2021-05-25T11:05:00.561341+00:00 app[web.1]: at Mongoose._promiseOrCallback (/app/node_modules/mongoose/lib/index.js:1135:10)
2021-05-25T11:05:00.561342+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:344:20)
2021-05-25T11:05:00.561343+00:00 app[web.1]: at Object.<anonymous> (/app/app.js:13:10)
2021-05-25T11:05:00.561343+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1068:30)
2021-05-25T11:05:00.561344+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
2021-05-25T11:05:00.561344+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:933:32)
2021-05-25T11:05:00.561344+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:774:14)
2021-05-25T11:05:00.561345+00:00 app[web.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
2021-05-25T11:05:00.561345+00:00 app[web.1]: at internal/main/run_main_module.js:17:47 {
2021-05-25T11:05:00.561346+00:00 app[web.1]: reason: TopologyDescription {
2021-05-25T11:05:00.561346+00:00 app[web.1]: type: 'ReplicaSetNoPrimary',
2021-05-25T11:05:00.561346+00:00 app[web.1]: setName: null,
2021-05-25T11:05:00.561347+00:00 app[web.1]: maxSetVersion: null,
2021-05-25T11:05:00.561347+00:00 app[web.1]: maxElectionId: null,
2021-05-25T11:05:00.561348+00:00 app[web.1]: servers: Map(3) {
2021-05-25T11:05:00.561348+00:00 app[web.1]: 'cluster0-shard-00-02.ocarv.mongodb.net:27017' => [ServerDescription],
2021-05-25T11:05:00.561348+00:00 app[web.1]: 'cluster0-shard-00-00.ocarv.mongodb.net:27017' => [ServerDescription],
2021-05-25T11:05:00.561349+00:00 app[web.1]: 'cluster0-shard-00-01.ocarv.mongodb.net:27017' => [ServerDescription]
2021-05-25T11:05:00.561350+00:00 app[web.1]: },
2021-05-25T11:05:00.561350+00:00 app[web.1]: stale: false,
2021-05-25T11:05:00.561350+00:00 app[web.1]: compatible: true,
2021-05-25T11:05:00.561350+00:00 app[web.1]: compatibilityError: null,
2021-05-25T11:05:00.561351+00:00 app[web.1]: logicalSessionTimeoutMinutes: null,
2021-05-25T11:05:00.561351+00:00 app[web.1]: heartbeatFrequencyMS: 10000,
2021-05-25T11:05:00.561351+00:00 app[web.1]: localThresholdMS: 15,
2021-05-25T11:05:00.561352+00:00 app[web.1]: commonWireVersion: null
2021-05-25T11:05:00.561352+00:00 app[web.1]: }
2021-05-25T11:05:00.561352+00:00 app[web.1]: }
2021-05-25T11:15:57.214740+00:00 app[web.1]: login api hit
2021-05-25T11:15:57.215001+00:00 app[web.1]: {}
2021-05-25T11:16:07.230564+00:00 app[web.1]: unspecified name
2021-05-25T11:16:07.247306+00:00 app[web.1]: /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:19
2021-05-25T11:16:07.247307+00:00 app[web.1]: throw error;
2021-05-25T11:16:07.247308+00:00 app[web.1]: ^
2021-05-25T11:16:07.247308+00:00 app[web.1]:
2021-05-25T11:16:07.247309+00:00 app[web.1]: ReferenceError: print is not defined
2021-05-25T11:16:07.247310+00:00 app[web.1]: at /app/routes/login.js:19:7
2021-05-25T11:16:07.247310+00:00 app[web.1]: at /app/node_modules/mongoose/lib/model.js:4863:16
2021-05-25T11:16:07.247310+00:00 app[web.1]: at /app/node_modules/mongoose/lib/model.js:4863:16
2021-05-25T11:16:07.247311+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:16:11
2021-05-25T11:16:07.247311+00:00 app[web.1]: at /app/node_modules/mongoose/lib/model.js:4886:21
2021-05-25T11:16:07.247312+00:00 app[web.1]: at /app/node_modules/mongoose/lib/query.js:4389:18
2021-05-25T11:16:07.247312+00:00 app[web.1]: at /app/node_modules/mongoose/lib/query.js:4424:14
2021-05-25T11:16:07.247313+00:00 app[web.1]: at cb (/app/node_modules/mongoose/lib/query.js:1895:14)
2021-05-25T11:16:07.247313+00:00 app[web.1]: at /app/node_modules/mquery/lib/collection/node.js:27:21
2021-05-25T11:16:07.247314+00:00 app[web.1]: at collectionOperationCallback (/app/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:160:26)
2021-05-25T11:16:07.247323+00:00 app[web.1]: at Timeout.<anonymous> (/app/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:185:11)
2021-05-25T11:16:07.247323+00:00 app[web.1]: at listOnTimeout (internal/timers.js:555:17)
2021-05-25T11:16:07.247324+00:00 app[web.1]: at processTimers (internal/timers.js:498:7)
2021-05-25T11:16:07.247324+00:00 app[web.1]: Emitted 'error' event on Function instance at:
2021-05-25T11:16:07.247324+00:00 app[web.1]: at /app/node_modules/mongoose/lib/model.js:4865:13
2021-05-25T11:16:07.247325+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:16:11
2021-05-25T11:16:07.247325+00:00 app[web.1]: [... lines matching original stack trace ...]
2021-05-25T11:16:07.247326+00:00 app[web.1]: at processTimers (internal/timers.js:498:7)
2021-05-25T11:16:07.314225+00:00 heroku[web.1]: Process exited with status 1
2021-05-25T11:16:07.401592+00:00 heroku[web.1]: State changed from up to crashed
2021-05-25T11:16:07.409072+00:00 heroku[web.1]: State changed from crashed to starting
2021-05-25T11:16:07.240945+00:00 heroku[router]: at=info method=POST path="/login" host=attendance-demo.herokuapp.com request_id=ac9410a0-ac64-420b-b4d5-803aaa1a3fb2 fwd="111.88.134.32" dyno=web.1 connect=1ms service=10035ms status=400 bytes=234 protocol=https
2021-05-25T11:16:18.897092+00:00 heroku[web.1]: Starting process with command `node app`
2021-05-25T11:16:30.471917+00:00 heroku[web.1]: State changed from starting to up
2021-05-25T11:16:30.423428+00:00 app[web.1]: Server is running
and here is the authenticate.dart file which i called on button click
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class AuthService{
Dio dio=new Dio();
login(name,password)async{
try{
return await dio.post('https://attendance-demo.herokuapp.com/login',data: {
"username":name,
"password":password
},options: Options(contentType:Headers.formUrlEncodedContentType)
);
}
on DioError catch(e){
Fluttertoast.showToast(msg: e.response.data['msg'],
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);
}
}
}
and here is the code of login button i created and calling login method from authentication class
RoundedButton(text:"Login", press: () {
AuthService().login(name,password).then((value){
if(value.data['success']){
token=value.data['token'];
Fluttertoast.showToast(msg: 'Authenticated',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
}
your mongodb Client is running on your local machine you must make a cloud base mongodb cluster like Atlas and change your mongo URI with cloud base cluster URI.
Solution
So, after spending lots of hours, I finally got solution! problem was my Mongodb was connected, issue was IP address so thanks to stackoverflow team I got solution from this link (Aka's solution) now I'm connected to my database!

Heroku cannot find mongoose module after deployment?

I have deployed a simple Nodejs app to Heroku and I keep getting an error in the application logs saying that the module "mongoose" cannot be found. I even provided a relative path instead of just saying require("mongoose"). The deployment succeeds and installs all the dependencies. The source code can be found here https://github.com/collinkleest/trim-io.
Here is the error log from heroku.
2020-10-17T02:01:42.000000+00:00 app[api]: Build started by user collinkleest#gmail.com
2020-10-17T02:01:59.000000+00:00 app[api]: Build succeeded
2020-10-17T02:01:59.493929+00:00 app[api]: Deploy af985be5 by user collinkleest#gmail.com
2020-10-17T02:01:59.493929+00:00 app[api]: Release v14 created by user collinkleest#gmail.com
2020-10-17T02:01:59.652847+00:00 heroku[web.1]: State changed from crashed to starting
2020-10-17T02:02:01.917601+00:00 heroku[web.1]: Starting process with command `npm start`
2020-10-17T02:02:04.175589+00:00 app[web.1]:
2020-10-17T02:02:04.175612+00:00 app[web.1]: > trim-io#0.0.1 start /app
2020-10-17T02:02:04.175612+00:00 app[web.1]: > node server.js
2020-10-17T02:02:04.175613+00:00 app[web.1]:
2020-10-17T02:02:04.369536+00:00 app[web.1]: internal/modules/cjs/loader.js:834
2020-10-17T02:02:04.369538+00:00 app[web.1]: throw err;
2020-10-17T02:02:04.369539+00:00 app[web.1]: ^
2020-10-17T02:02:04.369539+00:00 app[web.1]:
2020-10-17T02:02:04.369539+00:00 app[web.1]: Error: Cannot find module '../node_modules/mongoose'
2020-10-17T02:02:04.369540+00:00 app[web.1]: Require stack:
2020-10-17T02:02:04.369540+00:00 app[web.1]: - /app/models/urlEntity.js
2020-10-17T02:02:04.369541+00:00 app[web.1]: - /app/server.js
2020-10-17T02:02:04.369541+00:00 app[web.1]: at Function.Module._resolveFilename (internal/modules/cjs/loader.js:831:15)
2020-10-17T02:02:04.369542+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:687:27)
2020-10-17T02:02:04.369542+00:00 app[web.1]: at Module.require (internal/modules/cjs/loader.js:903:19)
2020-10-17T02:02:04.369543+00:00 app[web.1]: at require (internal/modules/cjs/helpers.js:74:18)
2020-10-17T02:02:04.369543+00:00 app[web.1]: at Object.<anonymous> (/app/models/urlEntity.js:1:18)
2020-10-17T02:02:04.369543+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1015:30)
2020-10-17T02:02:04.369544+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
2020-10-17T02:02:04.369544+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:879:32)
2020-10-17T02:02:04.369545+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:724:14)
2020-10-17T02:02:04.369545+00:00 app[web.1]: at Module.require (internal/modules/cjs/loader.js:903:19) {
2020-10-17T02:02:04.369545+00:00 app[web.1]: code: 'MODULE_NOT_FOUND',
2020-10-17T02:02:04.369546+00:00 app[web.1]: requireStack: [ '/app/models/urlEntity.js', '/app/server.js' ]
2020-10-17T02:02:04.369546+00:00 app[web.1]: }
2020-10-17T02:02:04.389361+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2020-10-17T02:02:04.389827+00:00 app[web.1]: npm ERR! errno 1
2020-10-17T02:02:04.398788+00:00 app[web.1]: npm ERR! trim-io#0.0.1 start: `node server.js`
2020-10-17T02:02:04.399025+00:00 app[web.1]: npm ERR! Exit status 1
2020-10-17T02:02:04.399280+00:00 app[web.1]: npm ERR!
2020-10-17T02:02:04.399493+00:00 app[web.1]: npm ERR! Failed at the trim-io#0.0.1 start script.
2020-10-17T02:02:04.399722+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-10-17T02:02:04.420468+00:00 app[web.1]:
2020-10-17T02:02:04.420707+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-10-17T02:02:04.420857+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2020-10-17T02_02_04_400Z-debug.log
2020-10-17T02:02:04.487055+00:00 heroku[web.1]: Process exited with status 1
2020-10-17T02:02:04.554273+00:00 heroku[web.1]: State changed from starting to crashed
Here is my server.js for reference as well:
const express = require("express");
const UrlEntity = require("./models/urlEntity");
const mongoose = require("./node_modules/mongoose");
const urlEntity = require("./models/urlEntity");
const app = express();
require('dotenv').config();
const mongoUri = "mongodb+srv://" + process.env.MONGO_USR + ":" + process.env.MONGO_PASS + "#" + process.env.MONGO_URL + "/" + process.env.MONGO_DB + "?retryWrites=true&w=majority";
mongoose.connect(
mongoUri,
{ useNewUrlParser: true, useUnifiedTopology: true}
);
app.use(express.json());
app.use(express.static('public'));
async function checkIdExists(id){
let exists = await UrlEntity.exists({uniqueId: id});
return exists;
}
function generateId(){
let randomId = Math.random().toString(20).substr(2, 8);
while(!(checkIdExists(randomId))){
randomId = Math.random().toString(20).substr(2, 8);
}
return randomId;
}
// redirect functionality
app.get("/:id", async (req, res) => {
if (req.params.id !== null || req.params.id !== undefined){
let doc = await UrlEntity.findOne({uniqueId: req.params.id});
res.redirect(doc.targetUrl);
} else {
res.redirect('/');
}
});
// create new url
app.post("/create-url", async (req, res) => {
console.log("in post");
let id = generateId();
await UrlEntity.create({uniqueId: id,
targetUrl: req.body.url,
dateCreated: req.body.date});
res.send(`${req.protocol}://${req.get('host')}/${id}`);
});
app.listen(process.env.PORT || 5000, () => {console.log("Trim.io API Started")});
You put mongoose in your devDependencies, which will be removed at runtime. (Link from your code) You need to move it to dependencies so that it will be available at runtime.
try changing the const mongoose = require("./node_modules/mongoose")
back to const mongoose = require("mongoose");
Don't forget to set your environment variables MONGO_USR, MONGO_PASS e.t.c on heroku settings. Your server will not start if the environment variable is not set.
Lastly I advice you use a connection string like this mongodb+srv://user:password#cluster2.bftwu.mongodb.net/databaseName
without concatenating

Error deploying node app to heroku

I'm relatively new to node, and have been having issues deploying a node web app to heroku... it seems to have to do with how I'm creating my mongoose connection in my server file. Here are the error logs I'm getting:
2016-01-06T00:41:30.384170+00:00 heroku[web.1]: State changed from starting to crashed
2016-01-06T00:43:56.191644+00:00 heroku[web.1]: State changed from crashed to starting
2016-01-06T00:43:57.774259+00:00 heroku[web.1]: Starting process with command `node server/server.js`
2016-01-06T00:44:00.138974+00:00 app[web.1]: listening on 4568
2016-01-06T00:44:00.172982+00:00 app[web.1]:
2016-01-06T00:44:00.172992+00:00 app[web.1]: /app/node_modules/mongoose/node_modules/mongodb/lib/server.js:236
2016-01-06T00:44:00.172994+00:00 app[web.1]: process.nextTick(function() { throw err; })
2016-01-06T00:44:00.172994+00:00 app[web.1]: ^
2016-01-06T00:44:00.172995+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:27017
2016-01-06T00:44:00.172996+00:00 app[web.1]: at Object.exports._errnoException (util.js:856:11)
2016-01-06T00:44:00.172997+00:00 app[web.1]: at exports._exceptionWithHostPort (util.js:879:20)
2016-01-06T00:44:00.172998+00:00 app[web.1]: at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)
2016-01-06T00:44:00.968046+00:00 heroku[web.1]: Process exited with status 1
2016-01-06T00:44:00.983259+00:00 heroku[web.1]: State changed from starting to crashed
And here is a shell of my server file:
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var entryController = require('./entries/entryController.js');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static(__dirname + '/../client'));
mongoose.connect('mongodb://localhost');
console.log('listening on 4568');
app.listen(4568);
Any advice would be greatly appreciated, thanks!
You're trying to connect to localhost:
mongoose.connect('mongodb://localhost');
Localhost means "this computer." Your database is not running in the same container on Heroku as your node app, so instead you need to connect to where your database really is hosted.
You may want to read a tutorial like:
https://scotch.io/tutorials/use-mongodb-with-a-node-application-on-heroku

Unable to connect to MongoHQ using Node.js + Expressjs

I've recently been trying to learn both Node.js and Mongo. I set up an account on Heroku, got a simple Node.js app running correctly and then took a dive into Mongo. I added on MongoHQ, but since then have been unable to connect the app to the database. Every time I run the app it crashes. At this point I just want to figure out what is wrong with my db connection or my use of mongoskin. Here is my current code:
var express = require('express');
var mongo = require('mongoskin');
var app = express.createServer(express.logger());
var conn = mongo.db(process.env.MONGOHQ_URL);
app.get('/', function(request, response) {
conn.collection('facts').find().toArray(function(err, facts){
if(err) throw err;
response.send(facts);
});
});
var port = process.env.PORT || 5000;
app.listen(port, function() {
console.log("Listening on " + port);
});
and my package file:
{
"name": "app1",
"version": "0.0.4",
"dependencies": {
"express": "3.x",
"mongoskin" : "0.1.x"
},
"engines": {
"node": "0.8.x",
"npm": "1.1.x"
}
}
and lastly the error code:
2012-12-11T17:42:32+00:00 app[web.1]: at Module.load (module.js:356:32)
2012-12-11T17:42:32+00:00 app[web.1]: at Module._compile (module.js:449:26)
2012-12-11T17:42:32+00:00 app[web.1]: at Object.<anonymous> (/app/node_modules/mongoskin/lib/mongoskin/db.js:162:28)
2012-12-11T17:42:32+00:00 app[web.1]: at Db.Object.defineProperty.get [as state] (/app/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/db.js:2125:31)
2012-12-11T17:42:32+00:00 app[web.1]: at Module.require (module.js:362:17)
2012-12-11T17:42:32+00:00 app[web.1]: at Module._compile (module.js:449:26)
2012-12-11T17:42:32+00:00 app[web.1]: TypeError: Cannot read property '_serverState' of undefined
2012-12-11T17:42:32+00:00 app[web.1]: at Function.Module._load (module.js:312:12)
2012-12-11T17:42:32+00:00 app[web.1]: at Object.<anonymous> (/app/node_modules/mongoskin/lib/mongoskin/index.js:2:10)
2012-12-11T17:42:32+00:00 app[web.1]:
2012-12-11T17:42:32+00:00 app[web.1]: at Object.Module._extensions..js (module.js:467:10)
2012-12-11T17:42:32+00:00 app[web.1]: at require (module.js:378:17)
2012-12-11T17:42:33+00:00 heroku[web.1]: Process exited with status 1
2012-12-11T17:42:33+00:00 heroku[web.1]: State changed from starting to crashed
Any help on what might be causing the problem would be highly appreciated.
You need to just update mongoskin library. Replace this line:
"mongoskin" : "0.1.x"
with
"mongoskin" : ">= 0.3.6"
More details here

Resources