node - deploying app to heroku with git - node.js

I am trying to deploy my app to heroku and I keep getting this error message saying that it "failed to detect app matching ......." and the push was rejected. I followed the way it said on the heroku website and I keep getting stuck on only that git push heroku master part I have tried doing some research I couldn't find a solution.
{
"name": "home-automation",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server/server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.15.3",
"johnny-five": "^0.11.3",
"socket.io": "^2.0.3"
}
}
Server.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var express = require("express");
var five = require("johnny-five");
var board = new five.Board({port:"COM4"});
const port = process.env.PORT || 3000;
app.use(express.static("public"))
io.on('connection', function (socket) {
console.log("New User Connected")
board.on("ready", function(){
socket.on("turnLightOn", function(data){
var led = new five.Led({
pin:"13"
});
if(data.status){
led.on();
}else{
led.off();
}
})
})
});
server.listen(port, function(){
console.log("Listening on port 3000")
});
index.js
var socket = io();
$("#toggle-light").on("click", function(){
$("#led").toggle();
if($("#led").css("display") == "none"){
var status = false
}else{
var status = true
}
socket.emit("turnLightOn", {
status
})
})
index.html
<html>
<head>
<title>Home Automation</title>
</head>
<body>
<h1>Home Automation</h1>
<button id="toggle-light">Toggle Light</button>
<div id="led" style="width:100px; height:100px; background:yellow;"></div>
<p id="moistureLevel"></p>
<script src="/socket.io/socket.io.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/js/index.js"></script>
</body>
</html>

This means that a package.json file isn't checked into the root of your git project, so Heroku is detecting that it isn't a Node.js app. You can see this locally:
git show master:package.json
To fix it, you'll want to be sure there is a package.json in the root of your project (where there is also a .git directory), and add it to git:
git add package.json
git commit -m 'track package.json'
The phrasing ('failed to detect set buildpack') could be improved. It should probably say 'failed to detect Node.js app'. When the buildpack's "detect" script is run (https://github.com/heroku/heroku-buildpack-nodejs/blob/master/bin/detect), it looks for a package.json file to verify that there's a node app available to build.

Related

nodemon not applying changes automatically to the app

When I save changes to the app nodemon says 'restarting due to changes'.
But when I refresh my localhost it does not apply the changes.
Everytime I have to run nodemon app.js to see the changes in my app. Why is it happening so?
Below is the app.js code:
const express = require('express')
// create express app
const app = express();
//register view engine
app.set('view engine','ejs');
//listen for requests
app.listen(3000);
app.use((req,res)=>{
console.log('new request made');
console.log('Host:',req.hostname);
console.log('Path:',req.path);
console.log('Method:',req.method);
});
//multiple get request handlers for diff webpages
app.get('/',(req,res)=>{
const blogs = [
{title: 'Yoshi finds eggs', snippet: 'Lorem ipsum dolor sit amet consectetur'},
{title: 'Mario finds stars', snippet: 'Lorem ipsum dolor sit amet consectetur'},
{title: 'How to defeat bowser', snippet: 'Lorem ipsum dolor sit amet consectetur'},
];
res.render('index',{title:'Home',blogs:blogs}); //the path for html webpage is always relative unless provided absolute. the root dir name of the path should be specified.
});
app.get('/about',(req,res)=>{
res.render('about',{title:'About'});
});
app.get('/blogs/create',(req,res)=>{
res.render('create',{title:'Create blog'});
});
app.get('/featured',(req,res)=>{
res.send('<p>Featured page</p>');
});
//redirects
app.get('/about-us',(req,res)=>{
res.redirect('/about'); //express send this response to the browser and automatically set status code to 301.
});
//setup 404 page(this functionality always at last beacuse this displays 404 page when any of the above urls is not found)
app.use((req,res) => {
res.status(404).render('404',{title:'Error 404'});
});
package.json code:
{
"dependencies": {
"ejs": "^3.1.6",
"express": "^4.17.2"
}
}
Versions:
nodemon 2.0.15,
node v16.13.2,
npm 8.1.2
Restarting server is one thing, refreshing browser is another thing. For server watching I use nodemon. Nodemon can see when changes occur in any types of files. But nodemon cannot refresh browser page. For this We may use two additional packages - connect-livereload,livereload.
npm install connect-livereload livereload
Below example:
Folder & File structure :
app.js
const path = require("path");
const livereload = require("livereload");
const connectLivereload = require("connect-livereload");
const express = require("express");
const port = 3000;
const liveReloadServer = livereload.createServer();
liveReloadServer.watch(path.join(__dirname, "views"));
liveReloadServer.server.once("connection", () => {
setTimeout(() => {
liveReloadServer.refresh("/");
}, 50);
});
const app = express();
app.use(connectLivereload());
app.set("view engine", "ejs");
app.get("/", (req, res) => {
res.render("index");
});
app.get("/about", (req, res) => {
res.render("about", { title: "About" });
});
//listen for requests
app.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`);
});
index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>ejs & express</title>
</head>
<body>
<main>
<div>
<h1>This is great and it works perfectly!</h1>
<p>Welcome to using EJS with nodemon and livereload</p>
</div>
</main>
</body>
</html>
about.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>ejs & express</title>
</head>
<body>
<main>
<div>
<h1>This is great and it works perfectly!</h1>
<p>Welcome to About Page !</p>
</div>
</main>
</body>
</html>
package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "nodemon app.js -e ejs",
"watch": "nodemon --ext ejs",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"connect-livereload": "^0.6.1",
"ejs": "^3.1.6",
"express": "^4.17.2",
"livereload": "^0.9.3"
},
"devDependencies": {
"nodemon": "^2.0.15"
}
}
npm run watch
We run app.js with command npm run watch
Now it works like a charm !
Output :

How to deploy socket io & express server on heroku

I'm trying to deploy socket io + express server on heroku for a chat application but i am facing a trouble while deploying the server .
First this is my server code
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
users = [];
connections = [];
server.listen(process.env.PORT || 3000);
console.log('Server running...');
io.sockets.on('connection',function(socket){
connections.push(socket);
console.log('Connected %s sockets connected ', connections.length);
//Disconnect
socket.on('disconnect', function(data){
users.splice(users.indexOf(socket.username),1);
connections.splice(connections.indexOf(socket),1);
console.log('Disconneted : %s sockets connected',connections.length);
});
});
This is my package.json file
{
"name": "",
"version": "1.0.0",
"description": "chat application",
"main": "index.js",
"scripts": {
"start": "node index"
},
"author": "",
"license": "ISC",
"dependencies": {
"socket.io": "*",
"express": "*"
}
}
But I'm getting this error
Cannot GET /
Had the same problem (socket.io with express and react).
You can add to server this line:
app.use(express.static('some path to a static file'));
e.g.
app.use(express.static('client/build'))
works for me assuming in package.json has this line at "scripts":
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
This error has nothing wrong deployed application. Your app still waits for connection on port 3000 (or port from process.env.PORT). App responds "Cannot GET /" because you don't have any routes.
To see how routes can be implemented look at this -> https://expressjs.com/en/starter/hello-world.html
To see how connect using socket.io (client part) look at this -> https://socket.io/get-started/chat/#Integrating-Socket-IO

Openshift node app error when restarting

I have a node/socket.io chat app hosted on openshift, and while it starts correctly if i ssh into the server and do "node main.js" (where main.js is the server script that starts the chat), I can't start the app on the server by web interface, where it would go on automatically; If i just start the app by ssh, it would stop working as soon as i exit the terminal.
I get this error when starting the app by the web interface:
Starting Node.js application...
Application is already stopped.
Warning! Could not start Node.js application!
Failed to execute: 'control restart' for /var/lib/openshift/57003fbe7628e1491d00011e/nodejs
In case it's relevant, my package.json file is
{
"name": "rainychat",
"version": "1.0.0",
"description": "rainychat, my chat app",
"main": "main.js",
"dependencies": {
"express": "^4.13.4",
"socket.io": "^1.4.5",
"validator": "^5.1.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "JG",
"license": "ISC"
}
And here you can see the files of the app by ftp:
I can't decode what that error means...
My main.js code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/chat.html'); // /home/redadmin/public_html/rainychat.com
console.log('enviado');
});
app.set('port', process.env.OPENSHIFT_NODEJS_PORT || 8080);
app.set('ip', process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1');
http.listen(app.get('port'), app.get('ip'), function () {
console.log('Listening on port ' + app.get('port'));
});
//... More code
If you're creating a new Node project, start with npm init to create the package.json file. You can add the --auto option to give it safe defaults.
Remember, the JSON file must be valid JSON, so test it with jsonlint or a tool like an online validator.
Any dependencies your project has should be spelled out in the package file. This is done automatically with things like npm install express --save.

Deploy route in node.js application in heroku without express.js

I have 3 files :
server.js containing node.js server (Using WebSocket-Node)
client.js containing websocket code
frontend.html containing the html content includes the client.js file.
package.json :
{
"name": "kapp",
"version": "1.0.0",
"description": "Lightweight peer to peer",
"main": "frontend.html",
"scripts": {
"test": "node server.js"
},
"engines": {
"node": "0.10.x"
},
"author": "Kaustav Ray",
"license": "MIT",
"dependencies": {
"websocket": "^1.0.19"
}
}
server.js
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
});
server.listen(1337, function() { });
wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(request) {
var connection = request.accept(null, request.origin);
connection.on('message', function(message) {
if (message.type === 'utf8') {
}
});
connection.on('close', function(connection) {
});
});
client.js
$(function () {
window.WebSocket = window.WebSocket || window.MozWebSocket;
var connection = new WebSocket('ws://127.0.0.1:1337');
connection.onopen = function () {
};
connection.onerror = function (error) {
};
connection.onmessage = function (message) {
try {
var json = JSON.parse(message.data);
} catch (e) {
console.log('This doesn\'t look like a valid JSON: ', message.data);
return;
}
// handle incoming message
};
});
Local Folder Structure:
.git
node_modules // containing websocket
client.js
frontend.html
server.js
package.json
But somehow my application is not running and showing application error !
I want to first start the nodejs server and open frontend.html.
As I am starting with nodejs and heroku for first time cannot understand the exact problem !
Is there a problem in routing or other things are causing this error ?
Is express.js mandatory for routing ?
Heroku requires that your either provide a Procfile, which is a simple file that tells Heroku how to actually start your app, or specify scripts.start in your package.json.
// Procfile
web: node server.js
// package.json
"scripts": {
"start": "node server.js"
},
https://devcenter.heroku.com/articles/nodejs-support#default-web-process-type
https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction

Application gets slow when I change server.js file Openshift

I created a node app in openshift, I connected through SSH, and I was able to push my code and I could change the server.js code for a simple hello world.
Server.js
#!/bin/env node
var http = require('http');
var serverIp = process.env.OPENSHIFT_NODEJS_IP;
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
//creating server
var server = http.createServer(function(req, res) {
res.writeHead('Content-Type', 'text/plain');
res.end('Simple example!!');
});
//listening
server.listen(port, serverIp, function() {
console.log('Server started on port ' + port + ' IP: ' + serverIp);
});
When push this new code, I'm not getting any errors.
And this is the package.json file
{ "name": "Hello_world",
"version": "1.0.0",
"description": "Hello world",
"engines": {
"node": ">= 0.6.0",
"npm": ">= 1.0.0"
},
"devDependencies": {},
"bundleDependencies": [],
"private": true,
"scripts": {
"start" : "node server.js"
},
"main": "server.js"
}
When I do this, the application gets very very slow (like 2/3 minutes of waiting), here's the link.
[http://avalecia-minisis.rhcloud.com/]enter code here1
But when I change the code for the original, everything's fine... :/
I don't see where the issue could be.
When deploying to OpenShift, your application's build process can be optimized (or tuned) in a variety of ways.
If you'd like to minimize downtime between deploys, you can try enabling the hot_deploy feature:
mkdir .openshift ; mkdir .openshift/markers ; touch .openshift/markers/hot_deploy
git add .openshift/markers/hot_deploy
git commit -m "enabling the hot_deploy marker to minimize downtime on OpenShift"
git push
Checking in your node_modules folder can also have a major impact on build time.
Turning on NPM_CONFIG_PRODUCTION is another approach that may help (see : Run npm install --production on OpenShift)

Resources