socket.io 'on' doesn't get fired with Nodejs server - javascript

server.js
const express_l = require('express');
const path_l = require('path');
const app_l = express_l();
const http_l = require('http');
const server_l = http_l.createServer( app_l);
const socketio_l = require('socket.io');
const io_l = socketio_l( server_l);
app_l.use( express_l.static( path_l.join( __dirname, 'public')) );
io_l.on( "connection", argSocket => { console.log('New websocket connection!'); });
var PORT = 3000 || process.env.PORT;
server_l.listen( PORT, ()=>{ console.log(`from express server on port ${PORT}!`) });
main.js
const socket = io_l();
chat.html
...
...
<script src = "/socket.io/socket.io.js"> </script>
<script src = "js/main.js"> </script>
</body>
</html>
package.json
{
"name": "chatcord",
"version": "1.0.0",
"description": "Realtime chat application built with Nodejs",
"main": "server.js",
"scripts": {
"start": "node server",
"dev": "nodemon server"
},
"author": "xyz",
"license": "MIT",
"dependencies": {
"express": "^4.18.1",
"moment": "^2.29.3",
"socket.io": "^4.5.1"
},
"devDependencies": {
"nodemon": "^2.0.16"
}
}
Now, when I refresh http://localhost:3000/ in browser, I don't see the console.log statement from the on function of socket.io.
Where am I going wrong? Please point out.

Your initialization is wrong. You have to create a new instance of the socket io server and then call it. Check the documentation for more.
https://socket.io/get-started/chat#integrating-socketio
const { Server } = require("socket.io");
const io = new Server(server);
io.on('connection', (socket) => {
console.log('a user connected');
});
Hopefully this helps.

this is from socket io documentation
https://socket.io/get-started/chat
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
io.on("connection", async (socket) => {
console.log("someone connected to socket")
//add listener here
socket.on("chat",(data)=> {
console.log(data)
})
});
httpServer.listen(port, host, () => {
console.log(`Server running on http://${host}:${port}`);
});
also this is the emit cheatsheet maybe useful for you
https://socket.io/docs/v3/emit-cheatsheet/

You're consoling on nodejs server so check your terminal for the output of the console.
You need to research how emitting events works in socket (helping material)

Related

Express router working fine locally but not on heroku

My express app works fine on the localhost but it does not work on Heroku.
When I added a line it stops working and
the line is
app.use("/api/product", require("./routes/product"))
Here is the code
Index.js
const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
app.get("/", (req, res) => {
res.send("responded")
});
app.use(express.json())
app.use("/api/product", require("./routes/product"))
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
product.js
const express = require("express");
const router = express.Router();
router.get("/", async (req, res) => {
try {
res.json({
status: 200,
message: "Data has been successfully fetched"
});
}
catch (error) {
console.log(error);
return res.status(400).send("server error")
}
})
module.exports = router;
package.json
{
"name": "backend-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.3"
}
}
Folder structure
You would wanna switch your route handlers place. Otherwise you will never rich your api, as the first catches all requests.
const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
app.use(express.json())
app.use("/api/product", require("./routes/product"))
app.get("/", (req, res) => {
res.send("responded")
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});

Unable to connect mongoDb to Express

I am making a registration form with the MERN stack, I am connecting Express app to mongoDB but I am getting error in connection.
I am following Thapa Technical video on YouTube, and I have done exactly what Thapa did, I don't know what is wrong in this, I am a beginner please help me.
app.js file:
const express = require('express');
const app = express();
require("./db/conn")
const port = process.env.PORT || 3000;
app.get("/", (req, res) => {
res.send("Welcome to Abdullah's webbsite")
});
app.listen(port, () => {
console.log(`Server is running at port no ${port}`)
})
conn.js file:
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/userRegistration", {
useNewUrlParser:true,
useUnifiedTopology:true,
useCreateIndex:true
}).then(() =>{
console.log(`Connection Successful`);
}).catch((e) => {
console.log(e);
})
package.json file:
{
"name": "registration-form",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev" : "nodemon src/app.js"
},
"author": "Abdullah",
"license": "ISC",
"dependencies": {
"express": "^4.17.3",
"hbs": "^4.2.0",
"mongoose": "^6.2.2"
}
}
console:
Server is running at port no 3000
MongoParseError: option usecreateindex is not supported
at parseOptions (C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongodb\lib\connection_string.js:289:15)
at new MongoClient (C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongodb\lib\mongo_client.js:62:63)
at C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\connection.js:784:16
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\connection.js:781:19)
at C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\index.js:340:10
at C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5 at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\ABDULLAH\Desktop\Registration Form\Registration form\node_modules\mongoose\lib\index.js:1140:10)
Please remove useCreateIndex option in connn.js:
mongoose.connect("mongodb://localhost:27017/userRegistration", {
useNewUrlParser:true,
useUnifiedTopology:true
}).then(() =>{
console.log(`Connection Successful`);
}).catch((e) => {
console.log(e);
})
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
let userModel;
// configure mongoose
mongoose.connect('mongodb://localhost:27017/userRegistration', (err) => {
if (err) {
console.log(`Error connecting to mongodb => `, err);
} else {
console.log(`Mongodb Connected successfully`);
}
});

str.CharAt is not a function - when trying to access server route

I'm not sure what I did, but I broke something. Trying to deploy an API to Heroku. Everything was fine locally but then I guess I did something wrong and now it's all broken. It works when I go just localhost:5000 and displays that page (which just says "hello world") but when I try to access anything with the API parameters eg: localhost:5000/data/2018-10/gen6ou it just sits. No error is shown in the console. In the terminal, where i ran the command: node index.js it displays: str.charAt is not a function but does not break the connection or anything.
index.js
const express = require('express');
const app = express();
const pool = require("./db"); //stores super secret db info
const cors = require("cors");
const PORT = process.env.PORT || 5500;
// middleware
app.use(cors());
app.use(express.json()); // => req.body
app.use(express.static('public')); //index.html, just says 'hello world'
// get the data
app.get("/data/:date/:tier", async (req, res) => {
try {
const { date, tier } = req.params;
const allData = await pool.query(
"SELECT * FROM smogon_usage_stats WHERE date=$1 AND tier=$2",
[date, tier]
);
const results = allData.rows;
const output = { "data": Object.fromEntries(
results.map(
item => [item.pokemon, item]
))
};
res.json(output);
} catch (error) {
console.log(error.message);
};
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}.`);
});
package.json
{
"name": "usage_server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"pg": "^8.5.1"
},
"engines": {
"node": "14.16.0",
"npm": "6.14.11"
},
"proxy": "http://localhost:5000"
}
db.js
const { Pool } = require('pg');
require("dotenv").config();
const devConfig = `postgresql://${process.env.PG_USER}:
${process.env.PG_PASSWORD}#${process.env.PG_HOST}:
${process.env.PG_PORT}/${process.env.PG_DATABASE}`;
const proConfig = {
connectionString: process.env.DATABASE_URL
};
const conn = new Pool({
connectionString: process.env.NODE_ENV === "production" ? devConfig : proConfig
});
module.exports = conn;
In production, your database config object is invalid - the connectionString contains another object (the proConfig).
You seem to be looking for either
const devConfig = {
connectionString: `postgresql://${process.env.PG_USER}:${process.env.PG_PASSWORD}#${process.env.PG_HOST}:${process.env.PG_PORT}/${process.env.PG_DATABASE}`
};
const proConfig = {
connectionString: process.env.DATABASE_URL
};
const conn = new Pool(process.env.NODE_ENV === "production" ? devConfig : proConfig);
or
const connectionString = process.env.NODE_ENV === "production"
? process.env.DATABASE_URL
: `postgresql://${process.env.PG_USER}:${process.env.PG_PASSWORD}#${process.env.PG_HOST}:${process.env.PG_PORT}/${process.env.PG_DATABASE}`;
const conn = new Pool({ connectionString });

Unable to connect MongoDB in Node JS application

My application was running just fine and was connected to mongoDB while developing a simple node js application. But suddenly it started showing this error. Here is a snap of the console:
Here is my file providing mongoURI, and it was working just fine before the error:
module.exports = {
mongoURI:
"mongodb+srv://glorious:glorious#cluster0-to57n.mongodb.net/test?retryWrites=true&w=majority"
};
Here is my server.js file:
const express = require("express");
const mongoose = require("mongoose");
const app = express();
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(db)
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
app.get("/", (req, res) => res.send("Hello World"));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
And here is my package.json file:
{
"name": "devconnector",
"version": "1.0.0",
"description": "A social network for developers",
"main": "server.js",
"scripts": {
"start": "node server.js",
"server": "nodemon server.js"
},
"author": "Utkarsh Shrivastava",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"gravatar": "^1.8.0",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.7.13",
"passport": "^0.4.0",
"passport-jwt": "^4.0.0",
"validator": "^12.1.0"
},
"devDependencies": {
"nodemon": "^2.0.1"
}
}
useNewUrlParser doc:
The useNewUrlParser Option
By default, mongoose.connect() will print out the below warning:
DeprecationWarning: current URL string parser is deprecated, and will
be removed in a future version. To use the new parser, pass option {
useNewUrlParser: true } to MongoClient.connect.
The MongoDB Node.js driver rewrote the tool it uses to parse MongoDB connection strings. Because this is such a big change, they put the new connection string parser behind a flag. To turn on this option, pass the useNewUrlParser option to mongoose.connect() or mongoose.createConnection().
mongoose.connect(uri, { useNewUrlParser: true });
mongoose.createConnection(uri, { useNewUrlParser: true });
You can also set the global useNewUrlParser option to turn on useNewUrlParser for every connection by default.
// Optional. Use this if you create a lot of connections and don't
want // to copy/paste `{ useNewUrlParser: true }`.
mongoose.set('useNewUrlParser', true);
To test your app with {useNewUrlParser: true }, you only need to check whether your app successfully connects. Once Mongoose has successfully connected, the URL parser is no longer important. If you can't connect with { useNewUrlParser: true }, please open an issue on GitHub.
useUnifiedTopology doc:
useUnifiedTopology
By default, mongoose.connect() will print out the below warning:
DeprecationWarning: current Server Discovery and Monitoring engine is
deprecated, and will be removed in a future version. To use the new
Server Discover and Monitoring engine, pass option {
useUnifiedTopology: true } to the MongoClient constructor.
Mongoose 5.7 uses MongoDB driver 3.3.x, which introduced a significant refactor of how it handles monitoring all the servers in a replica set or
sharded cluster. In MongoDB parlance, this is known as server
discovery and monitoring.
To opt in to using the new topology engine, use the below line:
mongoose.set('useUnifiedTopology', true);
If you find any unexpected
behavior, please open up an issue on GitHub.
So you need to pass both options to mongoose.connect:
// Connect to MongoDB
mongoose
.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
...
your server.js file
const express = require('express');
const connectDB = require('./config/db');
const app = express();
// connect Database
connectDB();
app.get('/', (req, res) => res.send('API Running...'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server Started On Port ${PORT}`));
db.js file under config folder
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');
const connectDB = async () => {
try {
await mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true
});
console.log('MongoDB Connected !!');
} catch (err) {
console.error(err.message);
// Exit process
process.exit(1);
}
};
module.exports = connectDB;
default.json under config folder
{
"mongoURI": mongodb://[username:password#]host1[:port1][,...hostN[:portN]][/[database][?options]]
}
you can check more on
Connection String URI Format for default.json
You are missing URL PARSER.
Just modify your code to
...rest of the code
// Connect to MongoDB
mongoose
.connect(db, {newUrlParser: true})
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
...rest of the code
Or you can also set it globally using
mongoose.set('useNewUrlParser', true);
Read more about it here
https://mongoosejs.com/docs/deprecations.html
I have Just Worked with Mondo DB.
This code may helps
add {useNewUrlParser:true} while connecting to MongoDb.see Mongo DB deprecations
your server.js file:
const express = require("express");
const mongoose = require("mongoose");
const app = express();
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
app.get("/", (req, res) => res.send("Hello World"));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
Hope this work fine, and will connect you mongo db.

How can I send file from postman to node js?

I want to upload file from postman to node js but I have problem.
POSTMAN
Write url,check post method,check form-data,check file,write file name and choose file
This is my code
app.js
const express = require('express');
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
app.use(fileUpload());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
router.js
router.post('/schedule/entry', function(req,res){
console.log(req.file.name);
});
Console return me undefined name, if I write this code
router.post('/schedule/entry', function(req,res){
console.log(req.file);
});
Return 'undefined'
Why?
package.json
{
"name": "nodejs-rest-api-authentication",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.16.1",
"csv-array": "0.0.22",
"csv-write-stream": "^2.0.0",
"express": "^4.14.1",
"express-fileupload": "^0.3.0",
"fast-csv": "^2.4.1",
"formidable": "^1.1.1",
"json2csv": "^3.11.5",
"jsonwebtoken": "^8.1.0",
"mysql": "^2.15.0"
}
}
server.js
const app = require('./app');
const port = process.env.PORT || 3000;
const server = app.listen(port, function() {
console.log('Server listening on port ' + port);
});
screenshots
screenshots
codeGit
Based on the discussion in the comment section:
const express = require('express')
const app = express()
const formidable = require('formidable')
const path = require('path')
const uploadDir = '' // uploading the file to the same path as app.js
app.post('/', (req, res) =>{
var form = new formidable.IncomingForm()
form.multiples = true
form.keepExtensions = true
form.uploadDir = uploadDir
form.parse(req, (err, fields, files) => {
if (err) return res.status(500).json({ error: err })
res.status(200).json({ uploaded: true })
})
form.on('fileBegin', function (name, file) {
const [fileName, fileExt] = file.name.split('.')
file.path = path.join(uploadDir, `${fileName}_${new Date().getTime()}.${fileExt}`)
})
});
app.listen(3000, () => console.log('Example app listening on port 3000!'))
Attached Screenshots:
Because of body-parser middleware file will be not available in req so you must use another middleware libraries like connect-busboy or multer or connect-multiparty

Categories