node server.js won't work - node.js

In my application I use :
"node": "7.2.1",
"npm": "4.4.4"
"#angular/cli": "1.4.9",
"#angular/core": "4.4.6"
I deploy my application in heroku, it build but when I run it, it show "Application error" when I check the heroku logs it shows
2018-03-05T18:09:46.391200+00:00 app[web.1]: - npm ERR! A complete log of this run can be found in:
2018-03-05T18:09:46.391279+00:00 app[web.1]: - npm ERR! /app/.npm/_logs/2018-03-05T18_09_46_383Z-debug.log
Where can I find those .log files ?
When I run "node server.js" it's still waiting without doing or showing any thing
here is my server.js file
// server.js
const express = require('express');
const app = express();
const path = require('path');
// Run the app by serving the static files
// in the dist directory
app.use(express.static(__dirname + '/dist'));
// Start the app by listening on the default
// Heroku port
app.listen(process.env.PORT || 8080);
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});
app.get('/*', function (req, res) {
var origin = req.get('origin');
res.sendFile(path.join(__dirname + '/dist/index.html'));
});
How to solve this problem?

The path to your log files are outputted here:
2018-03-05T18:09:46.391279+00:00 app[web.1]: - npm ERR! /app/.npm/_logs/2018-03-05T18_09_46_383Z-debug.log
To see the entire log file run this command:
cat /app/.npm/_logs/2018-03-05T18_09_46_383Z-debug.log
Hopefully that will help you find the issue.
Also, make sure to run
ng build
before trying to serve the compiled output.

Related

Failed at the app#1.0.0 start script This is probably not a problem with npm. There is likely additional logging output above

Hi Guys, I have created a little project of Mern stack. I am deploying it correctly on Heroku. But as soon as I am checking her on Heroku after deploying, then Failed to load resource: the server responded with a status of 503 (Service Unavailable) error is coming.
But as soon as I run heroku local in cmd after deploying then it is working correctly. I am giving below the heroku setup code. Please guide me. please ........
package.sjon file of backend
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "npm install && node index",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"dependencies": {
"config": "^3.3.1",
"express": "~4.16.1",
"express-fileupload": "^1.1.7-alpha.3",
"mongoose": "^5.9.12",
"nodemailer": "^6.4.6"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Index.js file of backend
var express = require('express');
var path = require('path');
const connectDB = require('./config/db')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var studentRouter = require('./routes/student')
var app = express();
connectDB();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('client/build'))
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
app.use('/', indexRouter);
app.use('/', studentRouter);
app.use('/users', usersRouter);
if (process.env.NODE_ENV == "production") {
app.use(express.static('client/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
}
var port = process.env.PORT || '8000';
app.listen(port, () => {
console.log(`server run port ${port}`);
})
module.exports = app;
All these codes are absolutely correct. I had a problem creating a cluster in mongodb atlas. The problem was that I had selected add current ip address while creating the cluster. Whereas I had to select allow from anywhere. So now I have selected the book. And now it is doing the right thing.
In my case, changing network access form anywhere in my MongoDB cluster, fixed the problem.
Also, don't forget to hit restart all dynos.

Problem when Client (react) and Server(nodejs) are in the same folder

I'm trying to deploy my web application, that has my client and server at the same main folder, to Heroku and I face some annoying problem that the server isn't serving the react build folder.
Here's my project folder tree:
/client
/api
app.js
server.js
app.js => routes, loading models, controllers, etc
server.js => server configuration
Here's the content of server.js, I believe the problem is here
const app = require('./app');
const path = require('path');
const cors = require('cors');
const express = require('express');
app.use(cors())
if (process.env.NODE_ENV === "production") {
console.log('we are on production!')
app.use(express.static('./client/build'));
app.get('*', (req, res) => {
console.log('redirecting to react app build')
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"))
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on PORT ${port}`))
It never gets to the console.log('redirecting to the react app build') part
When I entered my heroku server I face the server side instead of my react build. why is that so?
I've just created a test project using your architecture. My project is running and uploaded on Heroku right now. I'm gonna detail all steps I just do to make it works according to given information.
So my project architecture :
client/ // from CRA
package.json
server.js
.env
Configure your environment variable :
heroku config:set NODE_ENV=production // this for production heroku
In my .env file I set local environment variables such as :
NODE_ENV=production
Here's my main package.json file which I defined a heroku-postbuild to create the client build folder.
{
"name": "foo",
"version": "1.0.0",
"main": "index.js",
"license": "mit",
"dependencies": {
"cors": "2.8.5",
"express": "4.17.1",
"path": "0.12.7"
},
"scripts": {
"start": "node server.js",
"heroku-postbuild": "cd client && yarn && yarn build"
}
}
And the server.js file, almost the same as the one provided
const path = require('path');
const cors = require('cors');
const express = require('express');
const app = express()
app.use(cors())
if (process.env.NODE_ENV === "production") {
console.log('we are on production!')
app.use(express.static('client/build'));
app.get('*', (req, res) => {
console.log('redirecting to react app build')
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"))
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on PORT ${port}`))
You can run Heroku in local by typing this command heroku local in will loaded the .env file with environment variables.
To test production Heroku you have to type heroku open. Don't forget to set up "production" environment variable with command I wrote above.
Everything's working fine. I can upload my code to Github if you want me to.

Can´t connect to MongoDb in deployment (Heroku): connect ECONNREFUSED 127.0.0.1:27017

My app runs fine locally but the server (connecting to the database) doesn´t when deployed on Heroku.
By reading the log and surfing in SO I think is because of the following line:
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/shareable-todo-new')
.then((res) => console.log(res)).catch((err) => console.log(err));
My package.json :
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node ./app.js",
"dev": "nodemon ./app.js",
"heroku-postbuild":"NPM_CONFIG_PRODUCTION=false npm install --prefix front && npm run build --prefix front"
},
Tried adding this in my package.json but hasn´t helped:
"heroku config":"set NPM_CONFIG_PRODUCTION=true"
My app.js :
const express = require('express')
const https = require('https')
const app = express();
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const path = require('path')
const routerLists = require('./routes/lists');
const routerTasks = require('./routes/tasks')
const routerUsers = require('./routes/users')
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/shareable-todo-new', { useNewUrlParser: true, useUnifiedTopology: true })
.then((res) => console.log(res)).catch((err) => console.log(err));
// fix a deprecated bugs
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);
mongoose.Promise = global.Promise;
// Serve static assets if In Production:
app.use(bodyParser.json())
app.use('/api', routerLists)
app.use('/api', routerTasks)
app.use('/api', routerUsers)
if(process.env.NODE_ENV === 'production'){
// set static folder:
app.use(express.static(path.join(__dirname, "front/build")))
app.get("*", (req,res) => {
res.sendFile(path.resolve(__dirname, 'front', 'build', 'index.html'))
})
}
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// middleware para admitir errores:
app.use((err,res) => {
res.status(422).send({
error: err.message
})
})
app.listen(process.env.PORT || 4000, () => console.log('express listening now...'))
If it´s of any help, when I try to do POST requests the chrome console gives error 500
When you develop and test on your local PC (localhost or 127.0.0.1), you have your code, development environment, the server and the MongoDB instance setup locally on port 27017(or any other). But when you deploy the code to Heroku and try to run your app, Heroku will definitely throw some kind of error because it has not configured any MongoDB instance on the server (that is .herokuapp.com). It is good if you find a way to create an instance which is really hard.
The best recommended way is to connect your application to the MongoDB cloud. As said in the above answer by Oleksandr, you have to create an account on mlab or MongoDB Atlas.
Place the following code snippet in the javascript file in which the code for starting your server is present.
//the following URL will be provided once you create an account on MongoDB Atlas and create
//a cluster.
mongoose.connect(`mongodb+srv://<database_user_name>:<password>#cluster.address/<db_name>?retryWrites=true&w=majority`,{
useNewUrlParser:true,
useUnifiedTopology:true //this line is not mandatory
}).then(()=>{
console.log('Connected to MongoDB Cloud :)');
})//catch errors if you want.
Other CRUD operations should work normally and make sure you have a good internet connection if you develop and make CRUD operations on MongoDB cloud from your localhost:port.
That should help! :)
Referring to 127.0.0.1 (or localhost) means your local machine. When you running your application on Heroku, 127.0.0.1 is the Heroku machine which does not contain MongoDB instance. You should use external server for hosting MongoDB, for example, https://mlab.com/
After deploying MongoDB to server, set environment variable (MONGODB_URI) to appropriate value

issue deploying node.js server to heroku

I am running into the error
An error occurred in the application and your page could not be served.
when running 'heroku open' command. On heroku dashboard it says deployed successfully but then it will not run 'it is working' from the app.get line of code.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');
const register = require('./controllers/register');
const signin = require('./controllers/signin');
const profile = require('./controllers/profile');
const image = require('./controllers/image');
const db = knex({
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'benjohnson',
password : '',
database : 'smart-brain'
}
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.get('/', (req, res)=> { res.send('its working!') })
app.post('/signin', signin.handleSignin(db, bcrypt))
app.post('/register', (req, res) => { register.handleRegister(req, res, db, bcrypt) })
app.get('/profile/:id', (req, res) => { profile.handleProfileGet(req, res, db)})
app.put('/image', (req, res) => { image.handleImage(req, res, db)})
app.post('/imageurl', (req, res) => { image.handleApiCall(req, res)})
app.listen(process.env.PORT || 3000, ()=> {
console.log(`app is running on port ${process.env.PORT}`);
})
When running the server.js file within the heroku cli i receive the error, when running 'heroku logs --tail' i receive this error?
> node#1.0.0 start /Users/benjohnson/.Trash
> nodemon server.js
sh: nodemon: command not found
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! node#1.0.0 start: `nodemon server.js`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the node#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likel
y additional logging output above.
npm WARN Local package.json exists, but node_modules missing, di
d you mean to install?
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/benjohnson/.npm/_logs/2019-09-25T14_11_11_91
0Z-debug.log
The error is about nodemon.
Open the package.json, is at the same folder with server.js
Find:
"scripts": {
"start": " nodemon server.js",
},
And replace it with:
"scripts": {
"start": "node server.js",
"start:dev": "nodemon server.js"
},
Upload again in Heroku.
When you want to run the project locally, just run in your terminal npm start:dev and it will load server.js with nodemon.

Docker - failed to connect to running image

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.

Resources