How to use socket io with node.js - node.js

I have deployed an app with Heroku. I have a chat. It work fine in local but not with the online app.
index.js in my server :
const express = require('express');
const bodyparser = require('body-parser');
const security = require('./middleware/security');
const userRouter = require('./routes/user');
const AnnonceRouter = require('./routes/annonce');
const securityRouter = require('./routes/security');
const commentRouter = require('./routes/comment');
const mailRouter = require('./routes/mail')
const path = require('path');
const isDev = process.env.NODE_ENV !== 'production';
const PORT = process.env.PORT || 5000;
const app = express();
const cors = require('cors');
var chat = require('https').createServer(app)
var io = module.exports.io = require('socket.io')(chat)
const SocketManager = require('./SocketManager')
io.on('connection', SocketManager)
if (process.env.NODE_ENV === 'production') {
app.use(express.static('../client/build')); // serve the static react app
app.use(cors());
app.use(bodyparser.json());
app.use(security.verifyToken);
app.use('/annonce', AnnonceRouter);
app.use('/user', userRouter);
app.use('/comment', commentRouter);
app.use('/mail', mailRouter);
app.get(/^\/(?!api).*/, (req, res) => { // don't serve api routes to react app
res.sendFile(path.join(__dirname, '../client/build/index.html'));
})
app.use('/', securityRouter);;
console.log('Serving React App...');
};
app.listen(PORT, function () {
console.error(`Node ${isDev ? 'dev server' : 'cluster worker '+process.pid}: listening on port ${PORT}`);
});
the file when i use it
const socketUrl = "https://teachonline.herokuapp.com"
export default class Layout extends React.Component {
constructor(props) {
super(props);
this.state = {
socket:null,
user:null
};
}
componentWillMount() {
this.initSocket()
}
/*
* Connect to and initializes the socket.
*/
initSocket = ()=>{
const socket = io(socketUrl)
socket.on('connect', ()=>{
console.log("Connected");
})
this.setState({socket})
}
I tried something different, but the result is still the same.
My request looks like that : https://teachonline.herokuapp.com/socket.io/?EIO=3&transport=polling&t=MpFHcqj
But i get a code 401 "Unauthorized"
If you have an idea of what am i doing wrong, i'm listening.

Instead of PORT_CHAT, use PORT.
const isDev = process.env.NODE_ENV !== 'production';
const PORT = process.env.PORT || 5000;
const PORT_CHAT = 3231;
const app = express();
const cors = require('cors');
var chat = require('https').createServer()
var io = module.exports.io = require('socket.io')(chat)
const SocketManager = require('./SocketManager')
io.on('connection', SocketManager)
chat.listen(PORT, ()=>{
console.log("Connected to port:" + PORT);
})

Related

How to add SSL (HTTPS) in my NodeJS server

I Have code like this.
const pino = require('pino')
const { Boom } = require('#hapi/boom')
const fs = require('fs')
const chalk = require('chalk')
require('dotenv/config')
const express = require('express')
const socket = require("socket.io");
const { toDataURL } = require('qrcode')
const mysql = require('mysql');
require('dotenv').config();
const request = require('request');
const { smsg } = require('./app_node/lib/myf')
const app = express()
const host = process.env.HOST
const port = parseInt(process.env.PORT)
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
const ser = app.listen(port, host, () => {
console.log(`Server is listening on http://${host}:${port}`)
})
const io = socket(ser);
how do i get my code to run on the https server
i want to run my server in https in nodejs

Heroku Cannot GET/

I deployed my project with Heroku and everything works correctly but when I refresh the page I received the error "Cannot GET /home". Is there anyone can help me? https://fresh-bio.herokuapp.com/
server.js:
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const app = express();
const connectDB = require("./config/connectDB");
const routesProducts = require("./routes/productsRoutes");
const routesUsers = require("./routes/userRoutes");
app.use(express.json());
app.use(cors());
connectDB();
app.use("/api/products", routesProducts);
app.use("/api/users", routesUsers);
app.use(express.static("client/build"));
app.get("/", function (req, res) {
res.sendFile("client/build/index.html");
});
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
const PORT = process.env.PORT || 5000;
app.listen(process.env.PORT, (err) =>
err
? console.error(err.message)
: console.log(`This server is running on localhost:${process.env.PORT}...`)
);
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const app = express();
const connectDB = require("./config/connectDB");
const routesProducts = require("./routes/productsRoutes");
const routesUsers = require("./routes/userRoutes");
app.use(express.json());
app.use(cors());
connectDB();
app.use("/api/products", routesProducts);
app.use("/api/users", routesUsers);
app.use(express.static(__dirname + "/client/build/"));
app.get(/.*/, (req, res) => {
res.sendFile(__dirname + "/client/build/index.html");
});
const PORT = process.env.PORT || 5000;
app.listen(process.env.PORT, (err) =>
err
? console.error(err.message)
: console.log(`This server is running on localhost:${process.env.PORT}...`)
);

No request body recieved from api call

This is my server.js -
const express = require("express");
const connectDB = require("./api/config/db");
const feedbackRouter = require("./api/routes/feedbackRouter");
const app = express();
const PORT = process.env.PORT || 5000;
connectDB();
app.use(feedbackRouter);
app.listen(PORT, () => {
console.log(`SERVER IS LIVE AT ${PORT}`);
});
Router (feedbackRouter.js)-
const express = require("express");
const router = express.Router();
router.post("/feedback", (req, res) => {
const feedbackData = req.body;
try {
console.log(feedbackData);
res.send(feedbackData);
} catch (error) {
res.status(400).send(error);
}
});
module.exports = router;
When I make an API call from the frontend(React) or Postman, the req.body gives me undefined and I don't see the content from the request anywhere.
The API call gives me status code of 200 in Postman.
Any idea what might be wrong here? Thanks in advance.
Add app.use(express.json()) to your Code.
Server.js:
const express = require("express");
const connectDB = require("./api/config/db");
const feedbackRouter = require("./api/routes/feedbackRouter");
const app = express();
const PORT = process.env.PORT || 5000;
app.use(express.json())
connectDB();
app.use(feedbackRouter);
app.listen(PORT, () => {
console.log(`SERVER IS LIVE AT ${PORT}`);
});
About express.json() method and its options:
https://expressjs.com/en/5x/api.html
You didn't use any body-parsers, they use to process the body of an request, documentation:
http://expressjs.com/en/resources/middleware/body-parser.html
Postman Request & Response:

Cannot GET , nodejs

I tired to solve this problem, when I browse localhost:5000 I got error like
Cannot GET /
//*****************app.js************
const express = require('express');
const mongoose = require('mongoose');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express();
const v1 = require('./routes/v1');
// ************* DB Config *************//
mongoose.connect(process.env.MONGO_DB_URL, {
useNewUrlParser: true,
useCreateIndex: true
});
mongoose.connection.on('connected' , () => {
console.log('Connected to the databse');
});
mongoose.connection.on('error' , (err) => {
console.error('Failed to connected to the databse: ${err}');
});
//**************Midlewares ***********//
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : true}));
//*************Routes *****************//
app.use('/api/v1', v1);
module.exports = app ;
//********** index.js ***************//
require('dotenv').config();
const app = require('./src/app')
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log('Server is ready for connections on port ${PORT}');
});
the problem here is you have no route at the root /
you have to add either your routes you defined or define a root route

breake timer on socket event

I need to break a timer on a socket event and my Nodejs Express Socket.io App looks like this:
app.js
const express = require('express') ;
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const api = require('./routes/api');
const users = io.of('/users') ;
const usersNamespace= (socket) => {
socket.on('disconnect',()=>{
});
}
users.on('connection',usersNamespace) ;
app.use('/api', api);
// make socket.io accessible in the express router
app.use((req,res,next)=>{
req.io = io;
req.users = users;
next();
});
server.listen('8000');
my ./routes/api.js file looks like:
var express = require('express');
var router = express.Router();
router.post('/test',req,res) {
// broadcast body of request to users namespace
req.users.emit('restreq',req.body) ;
var timer = setInterval(()=>{
console.log('hello');
}, 5000);
res.status(200).json('received') ;
}
module.exports = router;
The question is how i can do clearInterval and stop the timer on a receiving socket event?
You can pass a function or object to deal with intervals as you do with users:
app.js
const express = require('express') ;
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const api = require('./routes/api');
const users = io.of('/drivers') ;
const timer = {
hInterval: null,
register: hInterval => {
timer.hInterval = hInterval
},
disable: () => {
clearInterval(timer.hInterval)
timer.hInterval = null
}
}
const usersNamespace = socket => {
socket.on('disconnect', () => {
timer.disable()
});
}
users.on('connection', usersNamespace) ;
app.use('/api', api);
// make socket.io accessible in the express router
app.use((req, res, next)=>{
req.io = io;
req.users = users;
req.timer = timer;
next();
});
server.listen('8000');
api.js:
var express = require('express');
var router = express.Router();
router.post('/test', req,res) {
// broadcast body of request to users namespace
req.users.emit('restreq',req.body) ;
req.timer.register(setInterval(() => {
console.log('hello');
}, 5000));
res.status(200).json('received') ;
}
module.exports = router;

Resources