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?
Related
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!! `);
});
});
Making a GET request to my own authenticating user users/{id}/tweets in nodeJS and using V2 Twitter api, returns only tweets posted by my own authenticating user id.
What I need?
To GET all tweets both posted by myself and the ones that are showing in my timeline from users I follow.
Basically, the same result as in Twitter V1 GET statuses/home_timeline
How can I get this in V2?
index.js
const express = require("express");
const app = express();
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(express.json()); // for parsing application/json
const Twit = require("twitter-lite");
const config = require("./config");
const client = new Twit(config.appConfig);
function getTimeLineTweetsInV2() {
return new Promise(async (resolve, reject) => {
try {
let result = await client.get("users/tweets/1497521946694717448");
resolve(result);
} catch (error) {
console.log("errorrrrrrrrrr is", error);
reject(error);
}
});
}
(async function BotMain() {
let tweetsReceived = await getTimeLineTweetsInV2();
console.log(tweetsReceived);
})();
app.listen(3000, () => {
console.log("listeing on port 3000");
});
config.js
const dotenv = require("dotenv");
const path = require("path");
const ENV_FILE = path.join(__dirname, ".env");
dotenv.config({ path: ENV_FILE });
const appConfig = {
//define subdomain of twitter api URL e.g. api.twitter.com, streams.twitter.com
version: "2",
extension: false,
consumer_key: process.env.apikey,
consumer_secret: process.env.apisecret,
access_token_key: process.env.accesstoken,
access_token_secret: process.env.accesstokensecret,
};
module.exports = {
appConfig,
};
package.json
{
"name": "twitter_app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.0.0",
"express": "^4.17.3",
"path": "^0.12.7",
"twitter-lite": "^1.1.0"
}
}
There is no equivalent to the home timeline API in v2 - yet. This is on the roadmap. You’ll need to use the v1.1 API, or, be patient until a new version is available.
I created one demo app with ReactJS, NodeJS, MongoDb and Express. Trying to deploy on heroku. It works fine, if i dont use mongo, but as soon as i introduced mongo db. I am getting error cannot GET /.
I am using mongodb atlas. Do I need heroku addon to use database?
server.js
// Import dependencies
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const MongoClient = require("mongodb").MongoClient;
const ObjectId = require("mongodb").ObjectID;
const mongodb = require('mongodb');
const fs = require('fs');
const moment = require("moment");
require('dotenv').config();
const CONNECTION_URL = process.env.MONGODB_URI || "mongodb+srv://<username>:<password>#cluster0.xzzno.mongodb.net/<dbname>?retryWrites=true&w=majority";
const DATABASE_NAME = "DBNAME";
const port = process.env.PORT || 5000;
const app = express();
// Set our backend port to be either an environment variable or port 5000
// This application level middleware prints incoming requests to the servers console, useful to see incoming requests
app.use((req, res, next) => {
console.log(`Request_Endpoint: ${req.method} ${req.url}`);
next();
});
// Configure the bodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Configure the CORs middleware
app.use(cors());
app.get("/test/", (request, response) => {
response.send({"name":"Hello Test!!!"});
});
var database, userSignUp;
app.listen(port, () => {
MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
if(error) {
throw error;
}
database = client.db(DATABASE_NAME);
userSignUp = database.collection("UserData");
console.log("Connected to `" + DATABASE_NAME + "`!");
});
})
package.json
{
"name": "testproject",
"version": "1.0.0",
"description": "Learning Deployment",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"client": "cd client && npm start",
"server": "nodemon server.js",
"dev": "concurrently --kill-others-on-fail \"npm run client\" \"npm run server\"",
"client:build": "cd client && npm run build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Username/TestProject.git"
},
"author": "Ankita Jaiswal",
"license": "ISC",
"bugs": {
"url": "https://github.com/Username/TestProject/issues"
},
"homepage": "https://github.com/Username/TestProject#readme",
"dependencies": {
"body-parser": "^1.19.0",
"concurrently": "^5.3.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"nodemon": "^2.0.7",
"moment": "^2.29.1",
"mongodb": "^3.6.3",
"mongoose": "^5.11.8"
}
}
procfile
web: npm run dev
have tried web: npm start as well.
Just from my limited experience, I've had the same issue and it turned out I forgot to configure my environment variables on Heroku, so my MONGO_URI was undefined. If not that, you can use the Heroku CLI and run heroku logs --tail from the root of your project and might be able to see more about what's going on.
const CONNECTION_URL = process.env.MONGODB_URI || "mongodb+srv://<username>:<password>#cluster0.xzzno.mongodb.net/<dbname>?retryWrites=true&w=majority";
The upper code is incorrect. You have to change < username > and < password > (both include < >) by your usename and your password! Example:
const CONNECTION_URL = process.env.MONGODB_URI || "mongodb+srv://kanechan25:kane02052409#cluster0.xzzno.mongodb.net/<dbname>?retryWrites=true&w=majority";
I created a chat room using socket.io within my express app and it's working fine in local host
when I deployed my application to heroku I get this error when I open the chat room
GET http://localhost:5000/socket.io/?EIO=3&transport=polling&t=N1PV-tt net::ERR_CONNECTION_REFUSED
here is my index.js file
var express = require("express")
var cors = require("cors")
var bodyParser = require("body-parser")
var app = express()
var mongoose = require("mongoose")
//var http = require('http').createServer(app);
var io = require('socket.io')(http)
var port = process.env.PORT || 5000
var server = app.listen(port);
var io = require('socket.io').listen(server);
var http = require('http');
let users = [];
let messages = [];
let index = 0;
app.use(bodyParser.json())
app.use(cors())
app.use(bodyParser.urlencoded({ extended: false }))
const mongoURI = 'mongodb+srv://1920:1920#cluster0-qyzs9.mongodb.net/liebherr?retryWrites=true&w=majority'
mongoose.connect(mongoURI, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err))
var Users = require("./routes/Users")
app.use("/users", Users)
//Socket connection
io.on('connection', (socket) => {
io.emit('noOfConnections', Object.keys(io.sockets.connected).length)
socket.on('disconnect', () => {
console.log(`a user has left the chat.`);
io.emit('noOfConnections', Object.keys(io.sockets.connected).length)
})
socket.on('chat-message', (msg) => {
socket.broadcast.emit('chat-message', msg)
})
socket.on('typing', (data) => {
socket.broadcast.emit('typing', data)
})
socket.on('stoptyping', () => {
socket.broadcast.emit('stoptyping')
})
})
// Static folder
app.use(express.static(__dirname + '/public/'));
app.get(/.*/);
and here is package.json file
{
"name": "express-demo",
"version": "1.0.0",
"description": "This is a full stack application",
"engines": {
"node": "13.1.0"
},
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"author": "Farouk Turki",
"license": "ISC",
"dependencies": {
"bcrypt": "^3.0.7",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongodb": "^3.5.2",
"mongoose": "^5.8.9",
"nodemon": "^2.0.2",
"socket.io": "^2.3.0"
}
}
Everything is working fine except the chatroom so I need to know why it's still using port 5000 in localhost
From the front end (socket.io client) you are setting the hostname as localhost. But a front end code is not run server-side, it is in client side(your browser/or any thin client), it can access only the resources that are accessible over the internet(or the resources which is accessible by the browser itself).
So, in your case, the connection code will look something like:
<script>
const socket = io('http://<your-heroku-public-url-for-the-express-server>');
// which typically is
const socket = io('http://randomname.herokuapp.com');
</script>
Given that http://randomname.herokuapp.com is the public url of your node js server.
I'm taking an online course on writing block-chain from scratch.
The course utilizes javascript and node.js.
I am very new to these technologies but followed the course so far to the T.
i'm pasting the relevant code - the app file (index):
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.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 blovk added: ${block.toString()}`);
res.redirect('/blocks');
});
app.listen(HTTP_PORT, () => console.log(`Listening on port ${HTTP_PORT}`));
p2pServer.listen();
and the code from p2p-server.js:
const Websocket = require('ws');
const P2P_PORT = process.env.P2P_PORT || 5001;
const peers = process.env.PEERS ? process.env.PEERS.split(',') : [];
//HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001 npm run dev
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 to peer-to-peer connections on: ${P2P_PORT}`);
}
connectToPeers() {
peers.forEach(peer => {
const socket = new Websocket(peer);
socket.on('open', () => this.connectSocket(socket));
});
}
connectSocket(socket){
this.sockets.push(socket);
console.log('socket connected');
}
}
module.exports = P2pServer;
when I try to run the following in the command line:
HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001 npm run dev
I get the following:
'HTTP_PORT' is not recognized as an internal or external command, operable program or batch file.
for some reason the process.env isn't picking up the input and passing it on to the app. What is wrong here?
Thanks!
EDIT: I was asked to add the package.json:
{
"name": "sf-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": [],
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^23.1.0",
"nodemon": "^1.17.5"
},
"dependencies": {
"body-parser": "^1.18.3",
"crypto-js": "^3.1.9-1",
"express": "^4.16.3",
"ws": "^5.2.0"
}
}
You are using:
$ HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001 npm run dev
It is showing an error, because the window powershell will not recognize this command..
Instead you should use:
set HTTP_PORT=3002 && set P2P_PORT=5002 && set PEERS=ws://localhost:5001 && npm run dev
I believe were doing the same course. I'm sure you've probably figured this out but I tried the same step in Git Bash instead of Powershell and it worked.