Deploy route in node.js application in heroku without express.js - node.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

Related

socket.io - Failed to load resource: net::ERR_CONNECTION_REFUSED

I'm building a forum where two users after connections can post a status then comment on them.
For comments, i used socket.io .
In console i'm getting this error each few seconds :
Failed to load resource: net::ERR_CONNECTION_REFUSED
GET http://localhost/socket.io/?EIO=4&transport=polling&t=O05nump net::ERR_CONNECTION_REFUSED
How to fix this error ?
I installed express, nodemon and socket.io in my socket server:
Socket server:
package.json
{
"name": "socket",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.3",
"nodemon": "^2.0.15",
"socket.io": "^4.4.1"
}
}
app.js
const io = require("socket.io")(4000, {
cors: {
origin: "http//localhost:3000",
},
});
io.on('connection', (socket) => {
console.log('A new user is connected !');
})
io.on('disconnect', () => {
console.log('User has left !');
});
Front:
Also, i installed socket.io-client in client (front), then in my web page, i added this code :
import { io } from 'socket.io-client'
export default () => {
//implement socket
const socket = useRef()
useEffect(() => {
socket.current = io("ws://localhost/4000")
}, [])
return (
//some html code
)
}
My project tree:
Project Forum
├── back
├── client
└──index.jsx
└── socket
└──package.json
└──app.js
Console Visual Studio Code:
Visual studio code's console shows this only how many times i refresh browser or ctrl+S the code:
[nodemon] starting 'node apde app.js'
You added a slash instead of semi-colon:
socket.current = io("ws://localhost:4000")
const socketio = require("socket.io");
const express = require("express");
const http = require("http");
const app = express();
const PORT = process.env.PORT || 2018;
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: "*",
methods: ["GET", "POST", "OPTIONS"]
}
});
server.listen(PORT, () => {
io.on("connection", socket => {
console.log("ok");
console.log(socket.id);
// io.in(roomID).emit()
socket.emit("WELCOME_MESSAGE", ` ${socket.id} welcome!! `);
});
});

Next Js cannot find module next

I created Next Js project. I deployed it to my CPanel. And I created server.js file on directory.
I called next module as require in server.js. But When I access to my website I catch an error.
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module 'next';
This error message.
My server.js code
const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const port = !dev ? process.env.PORT : 3000;
// Create the Express-Next App
const app = next({ dev });
const handle = app.getRequestHandler();
app
.prepare()
.then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
handle(req, res, parsedUrl);
console.log("pathname", pathname);
}).listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
})
.catch((ex) => {
console.error(ex.stack);
process.exit(1);
});
My package json
{
"name": "projectName",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
},
"dependencies": {
"express": "^4.17.1",
"next": "10.0.6",
"react": "17.0.1",
"react-dom": "17.0.1"
}
}
What should i do?
Thank you.
Best regards
Add this in your package.json dependency section : "#next/env": "^12.0.7"
I've already had problems publishing a next application other than on vercel. To fix the error I had to create a docker in order to publish the application. In case someone doesn't answer with a more viable solution, I recommend looking into using a docker.

Error occured while trying to proxy to: http://localhost:4200/api/*

I am running my Angular Project on npm start and expect it to listen simultaneously to port 3000 (that is suppose to listen automatically to anything that is in the api folder).
Anyway, it looks like it is trying to listen to the port, but it keeps catching an error for who knows what reason
Doing a node BLL.js directly to see if there is a JSON output works like a charm, but having the REST api work does not seem to work weirdly.
package.json
{
"name": "project-vas",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxyConfig.json",
"build": "ng build --env=prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
proxyConfig.json
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"changeOrigin": true
}
}
api/DBConnection.js
exports.config = function()
{
return config = {
user: 'username',
password: 'password',
server: 'localhost',
database: 'databaseName'
};
}
api/BLL.js
const express = require('express');
const path = require('path');
const sql = require('mssql');
const app = express();
const connection = require('./DBConnection');
let config = connection.config();
const port = process.env.PORT || 3000;
app.use(express.static(__dirname + '/dist/ProjectName/'));
app.get('/*', (require, res) => res.sendFile(path.join(__dirname)));
app.get('api/usertypes', function (req, res) {
sql.connect(config, function (err) {
if (err) { console.log(err); }
else {
var request = new sql.Request();
request.query('sp_GETUSERTYPES', function (err, recordset) {
if (err) {
console.log(err);
}
res.send(recordset);
});
}
});
});
environment.ts
export const environment = {
production: false,
api:"http://localhost:3000",
};
Just the expected Stored Procedure output in the shape of a JSON array.
But 'Error occured while trying to proxy to: localhost:4200/api/usertypes' keeps getting returned whenever I try to test it on Postman.

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

Websocket server not starting concurrently with node server

I'm trying to write a simple WebSocket server app based in Nodejs, but I am unable to get it started when I run npm run dev.
This is my package.json file:
"name": "lg-chain",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest --watchAll",
"dev-test": "nodemon dev-test",
"start": "node ./app",
"dev": "nodemon ./app"
},
"keywords": [],
"license": "MIT",
"devDependencies": {
"jest": "24.1.0",
"nodemon": "1.18.9"
},
"dependencies": {
"body-parser": "1.18.3",
"crypto-js": "3.1.9-1",
"express": "4.16.4",
"ws": "6.1.3"
}
}
I developed both an http server and websocket server and my expectation is that they both will start when I run that command I mentioned above.
Below is my websocket server:
const Websocket = require('ws');
const P2P_PORT = process.env.P2P_PORT || 5001;
const peers = process.env.PEERS ? process.env.PEERS.split(',') : [];
class P2pServer {
constructor(blockchain) {
this.blockchain = blockchain;
this.sockets = [];
}
listen() {
const server = new Websocket.Server({ port: P2P_PORT });
server.on('connection', socket => this.connectSocket(socket));
this.connectToPeers();
console.log(`Listening for peer-to-peer connections on: ${P2P_PORT}`);
}
connectToPeers() {
peers.forEach((peer) => {
const socket = new Websocket(peer);
socket.on('open', () => this.connectSocket);
});
}
connectSocket(socket) {
this.sockets.push(socket);
console.log('Socket connected');
}
}
module.exports = P2pServer;
And this is my express server:
const express = require('express');
const bodyParser = require('body-parser');
const Blockchain = require('../blockchain');
const P2pServer = require('./p2p-server');
const HTTP_PORT = process.env.HTTP_PORT || 3001;
const app = express();
const bc = new Blockchain();
const p2pServer = new P2pServer(bc);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/blocks', (req, res) => {
res.json(bc.chain);
});
app.post('/mine', (req, res) => {
const block = bc.addBlock(req.body.data);
console.log(`New block added: ${block.toString()}`);
res.redirect('/blocks');
});
app.listen(HTTP_PORT, () => console.log(`Listening on port ${HTTP_PORT}`));
p2pServer.listen();
My express server starts up, but absolutely nothing happens with my websocket server. I don't get any errors anywhere. How do I begin troubleshooting this with websockets?

Resources