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.
Related
Trying to make my first Vue application, simple game with MEVN stack. Working perfect interacting with backend on development environment, however when hosting it doesn't fetch the data from the server.
Anyone able to point out what I have incorrect with the below?
More info below:
File structure:
/root
|- config.js
|- server.js
|- package.json + package-lock.json
|- client/
|- vue.config.json
|- ... (rest of dist, src, node_modules, public etc.)
|- models/
|- Elf.js + HighScore.js
|- routes/
|- api/
|- elf.js + highScore.js
config.js
module.exports = {
hostUrl: process.env.HOST_URL,
mongoURI: process.env.MONGO_URI,
PORT: process.env.PORT || 3000,
};
server.js
const express = require("express");
const app = express();
const port = 3000;
const mongoose = require("mongoose");
const { PORT, mongoURI } = require("./config.js");
// routes
const Player = require("./routes/api/player");
const Elf = require("./routes/api/elf");
const HighScore = require("./routes/api/highScore");
// cors is a middleware that allows us to make requests from our frontend to our backend
const cors = require("cors");
// morgan is a middleware that logs all requests to the console
const morgan = require("morgan");
// body-parser is a middleware that allows us to access the body of a request
const bodyParser = require("body-parser");
const path = require("path");
app.use(cors());
// use tiny to log only the request method and the status code
app.use(morgan("tiny"));
app.use(bodyParser.json());
// chek if we are in production
if (process.env.NODE_ENV === "production") {
// check if we are in production mode
app.use(express.static("client/dist"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "dist", "index.html"));
});
}
// test if server is running and connected to mongoDB
app.get("/", (req, res) => {
res.send("Hello World!");
});
// app.get("/", (req, res) => {
// res.send("Hello World!");
// });
// use routes
app.use("/api/", Player);
app.use("/api/", Elf);
app.use("/api/", HighScore);
mongoose
.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useUnifiedTopology: true,
})
.then(() => console.log("MongoDB connected..."))
.then(() => {
// log uri to console
console.log(`MongoDB connected to ${mongoURI}`);
})
.catch((err) => console.log(err));
app.listen(PORT, () => {
console.log(`Example app listening at ${PORT}`);
});
package.json
{
"name": "week1",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"server": "nodemon server.js --ignore 'client/'",
"client": "npm run serve --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"start": "node server.js",
"build": "npm install --prefix client && npm run build --prefix client"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.1",
"bootstrap": "^5.2.3",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"mongoose": "^6.7.5",
"morgan": "^1.10.0",
"portal-vue": "^2.1.7"
},
"devDependencies": {
"concurrently": "^7.6.0",
"nodemon": "^2.0.20"
}
}
Running within my dev environment at root dir using 'npm run dev', the app works flawlessly send/ receive data from mongoDB during this time. This starts up http://localhost:8080/. Also tried install of 'npm install -g serve' and running 'serve -s dist', this starts up serving at localhost:36797 and working flawlessly too.
I have tried to setup on Vercel & Render, both giving me the same issue where I'm not getting much feedback and the data isn't being fetched. Anyone else has this issue before?
I've been trying to deploy my Express application on Heroku and the build gets created successfully but when I try to open it, I'm greeted with an error message that basically states that the page could not be served.
So, I run heroku logs --tail and then I get the following error messages :
One half of the error messages
Remaining half of the error messages
File Tree
Procfile
web: node server.js
Package.json
{
"name": "conduit-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"nodemon": "^2.0.12",
"pg": "^8.7.1",
"pg-hstore": "^2.3.4",
"redux-persist": "^6.0.0",
"sequelize": "^6.6.5"
},
"devDependencies": {
"cross-env": "^7.0.3"
}
}
server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { sequelize } = require('./src/entities/User/User');
const db = require('./src/config/Database');
const feedRoute = require('./src/routes/Feed/Feed');
const usersRoute = require('./src/routes/Users/Users');
const userRoute = require('./src/routes/User/User');
const articlesRoute = require('./src/routes/Articles/Articles');
const profilesRoute = require('./src/routes/Profiles/Profiles');
const commentsRoute = require('./src/routes/Comments/Comments');
const app = express();
app.use(cors());
app.use(bodyParser.json());
// Routes
app.use('/api/feed', feedRoute);
app.use('/api/users', usersRoute);
app.use('/api/user', userRoute);
app.use('/api/articles', articlesRoute);
app.use('/api/profiles', profilesRoute);
app.use('/api/articles', commentsRoute);
// REQUESTS
app.get('/', async (req,res) => {
res.json('Yooooooooooo')
try {
await db.authenticate();
console.log('Connection has been established');
} catch(err) {
console.log('Error');
}
})
// To START sequelize and also wipes the DB clean
// async function main() {
// await sequelize.sync({force: true})
// }
// main()
// TO START sequelize
const PORT = process.env.PORT || 3000;
app.listen(PORT , () => {
console.log(`App is listening to ${PORT}`);
})
I've tried modifying my procfile and removing and re-installing the modules but the problem still persists.
I've been stuck on this for days now and any sort of help would be highly appreciated.
Looks like you problem is your pointing the main in package.json to a file that doesn't exist.
Package.json
"main": "index.js"
Your app seems to deploy from you server.js file.
The main field is a module ID that is the primary entry point to your program.
as per documentation: https://docs.npmjs.com/cli/v7/configuring-npm/package-json#main
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 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?