emitting data using SocketIO in a node app across routes/pages - javascript

A form in the index.html will make a post request to the /history route and fetch the data from the MongoDB database:
server.js:
const express = require('express');
const app = express();
const path = require('path');
const http = require('http');
const https = require('https');
const server = http.createServer(app);
const io = require('socket.io')(server);
app.get('/history', (req, res) => {
res.sendFile(__dirname + '/client/history.html');
});
app.post("/history", (req, res)=> {
// fetch data from database
io.emit('data-history', data)
}
In the history.js:
const socket = io('http://localhost:3000');
io.on('data-history', (data) => {
// render data to the page
}
Somehow the data cannot be transferred from server.js to history.js. I am aware that the socket got disconnected when I am switching pages,

Related

downloaded file corrupted by getting response using node.js and express

I want to download zip file by response using Node.js and express. I could downloaded it but it coruppted. I made 2 servers, one is for data storing and the other is front-end. I can't put the zip file on front-end server so I need to get it by response. following is the code:
for frontend (front-end-server)
const express = require("express");
const app = express();
const http = require('http');
const server = http.createServer(app);
const request = require('request');
app.get("/api/download", (req, res) => {
request('http://192.168.10.888:8088/getfile', (error, response, body) =>
{
res.set({
'Content-Type': 'application/zip',
'Content-Disposition': 'attachment; filename="sample.zip"'
});
res.send(body);
});
});
app.get('/', (req, res) => res.send('Hello app'));
app.listen(8081, () => console.log('Listening on port 8081'));
for data storing (data-server)
var fs = require('fs');
var http = require('http');
const express = require("express");
const app = express();
app.get('/getfile', function (req, res)
{
res.sendFile("/data/sample.zip");
});
app.get('/', (req, res) => res.send('Hello'));
app.listen(8088, () => console.log('Listening on port 8088'));
data-server just return the file as stream and front-end-server get it by http-request and return it to browser so I expected download the zip file by simply type following URL
http://192.168.10.97:8081/api/download

How do I fix a server side socket.io error?

I have the following lines of code in my index.js file:
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io').listen(server);
When I start my server with:
node --inspect server/index.js
I get:
TypeError: require(...).listen is not a function.
Any and all help appreciated!
You need http server.
The correct way to start a socket server is,
const express = require("express");
const http = require("http");
const app = express();
const server = http.createServer(app)
const socketio = require('socket.io')
const io = socketio(server);
io.on("connection", socket => {
console.log("connected");
socket.on("welcome", (data) => {
console.log("welcome message", data);
})
});
server.listen(3000, () => console.log(`listen on port ${port}`))
The client,
const io = require("socket.io-client");
let socket = io.connect("http://localhost:3000");
socket.emit("welcome", "Hi");

Adding socket.io to an existing Express project (with React on the front)

I have an existing project written in Express, where I've made a messaging system. Everything was working on POST/GET methods (to send and receive the messages).
I wanted to make them appear in real time, so I installed socket.io both on the client and server side. In my server.js I added these lines:
const http = require("http");
const io = require("socket.io");
const server = http.createServer();
const socket = io.listen(server);
and changed my app.listen(...) into server.listen(...).
Added also:
socket.on("connection", socket => {
console.log("New client connected");
socket.on('test', (test) => {
console.log('test-test')
});
socket.emit('hello', {hello:'hello!'});
socket.on("disconnect", () => console.log("Client disconnected"));
});
On the front part I put such code in the componentDidMount method:
const socket = socketIOClient();
socket.emit('test', {test:'test!'})
socket.on('hello', () => {
console.log('aaa')
})
Now I got 2 problems. Although the console.log() works correctly, I get an error on the React app:
WebSocket connection to 'ws://localhost:3000/sockjs-node/039/lmrt05dl/websocket' failed: WebSocket is closed before the connection is established.
Is that normal?
Also, when I change app.listen(...) into server.listen(...) in the server.js file, my routing stops working. All the POST and GET methods don't work, because the server is responding endlessly. Is that possible to use the socket.io just on a specific method in a specific routing file?
I keep my routes that way: app.use('/api/user', user); where user is a router file.
UPDATE:
full server.js require:
const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const bodyparser = require('body-parser');
const passport = require('passport');
const user = require('./routes/api/v1/User');
const company = require('./routes/api/v1/Company');
const http = require("http");
const io = require("socket.io");
const app = express();
dotenv.config();
app.use(passport.initialize());
require('./config/seed');
require('./config/passport')(passport);
const server = http.createServer();
const socket = io.listen(server);
You're not initializing server properly. Try making the following change
// const server = http.createServer();
const server = http.createServer(app);
and make sure you listen on server and not io
server.listen(PORT_GOES_HERE)
[UPDATE]
Working Example:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
// WARNING: app.listen(80) will NOT work here!
// DO STUFF WITH EXPRESS SERVER
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
For more details check this: https://socket.io/docs/

How to call a socket.on() from a separated file

I'm trying to call a socket.on() event from an external .js file and I can't figure out what I'm missing...
I'm using NodeJS with ExpressJS.Below are the files:
app.js(the server file)
const fs = require('fs');
const express = require('express');
const app = express();
const http = require('http').Server(app);
var io = require('socket.io')(http);
....
//Socket Io functions
const ioObj = require( './library/io.js')(app, express, io);
// This route will be used to print the type of HTTP request the particular Route is referring to
router.use(function (req, res, next) {
console.log("/" + req.method);
next();
});
....
/library/io.js (sockets file)
module.exports = function(app, express, io){
io.on('connection', async function(socket) {
socket.on('refreshPage', function(){
console.log("page should now be refreshed !!");
socket.emit("refreshPageNow");
});
....
});
}
What I'm trying to do is to call/access the refreshPage event from /library/io.js so I can send further a "refresh webpage" signal.
I tried to do something like :
io.sockets.emit("refreshPage");
and
ioObj.sockets.emit("refreshPage");
But didn't work...

Express Post Request 404

I'll try to make this as to the point as possible. I am trying to make a post request to my express backend. All of the post requests here work, except for "/addpayment". Here is my file called 'router.js'
module.exports = function(app) {
app.post('/signin', requireSignin, Authentication.signin)
app.post('/signup', Authentication.signup)
app.post('/addpayment', function(req, res, next) {
res.send({ message: 'why................' })
})
}
Here is my main 'server.js' file
const express = require('express')
const http = require('http')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const app = express()
const router = require('./router')
const mongoose = require('mongoose')
const cors = require('cors')
// DB Connect
mongoose.connect('mongodb://localhost/demo-app')
// App
app.use(morgan('combined'))
app.use(cors())
app.use(bodyParser.json({ type: '*/*' }))
router(app)
// Server
const port = process.env.PORT || 3090
const server = http.createServer(app)
server.listen(port)
console.log('Server has been started, and is listening on port: ' + port)
I get a 404 in postman, and inside my app browser console. I am using passport in my other routes. I already tried running it through passport when I have a JWT token, and same thing(a 404).
I have already looked at all Stack Overflow/Github posts on the first few pages of google results, with no solution for my use case.
I have made a simplified version of your server and everything works as expected. Only difference that I have made is that I am not creating http server like you, but just calling app.listen
here is working example
router.js
module.exports = function(app) {
app.post('/addpayment', function(req, res, next) {
res.send({message: 'why................'})
})
};
server.js
var express = require('express');
var router = require('./router');
var app = express();
router(app);
//init server
app.listen(3000, function() {
console.log("Server running on port 3000");
});

Categories

Resources