How to add SSL (HTTPS) in my NodeJS server - node.js

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

Related

NodeJS app on namecheap keeps displaying "It works! NodeJS 10.24.1"

Its supposed to display "OK" as per the codes instructions, but displays "It works!
NodeJS 10.24.1"
Here is the code:
const { json } = require("body-parser");
var express = require("express")
var app = express()
app.listen(3000)
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
var cookieParse = require("cookie-parser");
const cookieParser = require("cookie-parser");
app.use(cookieParser())
const cock = require("chrome-cookies-secure")
const port = 3001;
app.set("port", port);
app.get('/',function (req,res){
res.send(200)
})
app.listen(app.get("port"), () =>
console.log("Started listening on %s", app.get("port"))
);
I tried different urls and different settings but none work. I expect it to say OK

Not able to connect socket.io in nodejs

Hi I am trying to setup a connection with socket.IO but not able to do so. At present I am not getting any error but the connection is not taking place.Please find below the relevant details :
app.js
const express = require('express');
require('./db/mongoose');
const functions = require("firebase-functions");
var bodyParser = require('body-parser');
const app = express();
const http = require('http').createServer(app);
var io = require('socket.io');
socket = io(http, {cors: {
origin: "http://localhost",
methods: ["GET", "POST"]
}
});
var cors = require("cors");
var cookieParser = require('cookie-parser');
var path = require('path');
app.use(cors());
const portCheck = process.env.PORT || 3001
socket.on('connection', function (socket) {
console.log('connected to socket');
socket.emit('greeting-from-server', {
greeting: 'Hello Client'
});
});
app.listen(portCheck, ()=> {
console.log('Server Listening to port:' + portCheck);
})
Changes should done for your code as follows:
Change app listen with server listen
wrap socket.on(//...) with io.on(//...)
replace this lines
const app = express();const http =
require('http').createServer(app);
with
var server = require('http').Server(app);
var io = require('socket.io')(server);
After the changes code is like follows.
const express = require('express');
require('./db/mongoose');
const functions = require("firebase-functions");
var bodyParser = require('body-parser');
const app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
socket = io(http, {cors: {
origin: "http://localhost",
methods: ["GET", "POST"]
}
});
var cors = require("cors");
var cookieParser = require('cookie-parser');
var path = require('path');
app.use(cors());
const portCheck = process.env.PORT || 3001
server.listen(portCheck, ()=> {
console.log('Server Listening to port:' + portCheck);
})
io.on('connection', (socket)=> {
socket.on('connection', function (socket) {
console.log('connected to socket');
socket.emit('greeting-from-server', {
greeting: 'Hello Client'
});
});
});
follow more information through this link. https://socket.io/get-started/chat.

Video stream from client to server in NodeJS

I'm currently developing an application to stream video feed from client to server in NodeJS. The server side code is as shown below
server.js
const express = require('express')
const app = express()
const morgan = require('morgan')
const server = require('http').Server(app)
const io = require('socket.io')(server)
const auth = require('./routes/auth')
const video = require('./routes/videoproc')(io)
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(morgan('dev'))
app.use("/users", auth)
app.use("/exam", video);
server.listen(3000)
videoproc.js
const express = require('express')
const video = express.Router()
const ss = require('socket.io-stream')
const fs = require('fs')
const path = require('path')
module.exports = (io) => {
video.post('/video', (req, res) => {
io.on('connection', (socket) => {
ss(socket).on('video', (stream, data) => {
const fileName = path.basename('test')
stream.pipe(fs.createWriteStream(fileName))
})
})
})
return video
}
This is the client side code
var io = require('socket.io-client');
var ss = require('socket.io-stream');
var fs = require('fs')
var socket = io.connect('http://localhost:3000/exam/video/');
var stream = ss.createStream();
var filename = './test.webm';
ss(socket).emit('video', stream, {name: filename});
fs.createReadStream(filename).pipe(stream);
As a test I've send a video feed to the server but the file is not being stored, some help to solve this issue is appreciated.
Server you should:
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(morgan('dev'))
// app.use("/users", auth)
app.use("/exam", video);
io.on('connection', (socket) => {
console.log('CONNECTED');
ss(socket).on('video', (stream, data) => {
console.log('RECEIVED');
const fileName = path.basename('test')
stream.pipe(fs.createWriteStream(fileName))
})
})
server.listen(3000)
and Client: param in a connect function is just "http://localhost:3000/", exclude route
var socket = io.connect('http://localhost:3000/');
var stream = ss.createStream();
var filename = './test.webm';
ss(socket).emit('video', stream, {name: filename});
fs.createReadStream(filename).pipe(stream);
At client: connect to a domain, not route:
ref
At server: you placed io.on on a route, io.on is just listen when you call the route. if you want run when server starting, you should place io.on outside the route

Getting unexpected CORS error with socket.io and React

I don't know what else to try
My server:
const express = require("express");
const http = require("http");
const app = express();
const server = http.createServer(app)
const cors = require('cors');
app.use(cors());
app.options('*', cors());
const socketio = require('socket.io')
const io = socketio(server);
io.on("connect", socket => {
console.log("hello");
socket.on("welcome ", (e) => {
console.log(e)
})
});
const port = 8081;
server.listen(port, () => console.log(`listen on port ${port}`))
in app react
import io from "socket.io-client";
let socket = io.connect("http://localhost:8081");
socket.emit("welcome", "connected");
react run port 3000
nodejs run port 8081
but everything I try throws error.

How to use socket io with 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);
})

Resources