I have an app with express (nodeJS).
Want to emit io.socket when write some data on DB, so need to emit in route file (ex. /routes/save.js)
this is my app.js
var express = require('express');
var save = require('./routes/save');
var http = require('http');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
......
io.on('connection', function(socket){
socket.on('newTweet', function(msg){
io.emit('newTweet', msg);
});
});
app.use('/save', save);
.....
module.exports = app;
server.listen(3000, function () {
var host = server.address().address
var port = server.address().port
})
Can you please help me to write io.socket.emit('event') in /routes/save.js ?
I found a way.
Before app.use('/save', save); needed to write following code in app.js
app.use(function(req, res, next) {
req.io = io;
next();
});
and after this get io from req parameter in save.js
for example
var express = require('express');
var router = express.Router();
router.post('/', function(req, res, next) {
.....
var io = req.io;
io.emit('newTweet', 'test');
.....
});
module.exports = router;
if you know better way than this one, please let me know.
You can just pass the io object to your routes like this:
var app = express();
var io = socket_io();
app.io = io;
require('./routes/index')(app,io);
import {createServer} from 'http';
import express from 'express';
import socketio from 'socket.io';
const server = createServer(app);
const io = socketio.listen(server);
app.use(function (req, res, next) {
req.io = io;
next();
})
app.get('/', function (req, res) {
const ioConnection = req.io;
ioConnection.emit('nouveau_client', body.pseudo);
});
io.sockets.on('connection', function (socket) {
socket.on('nouveau_client', function (user) {
socket.broadcast.emit('nouveau_client', user.pseudo);
});
});
server.listen(3000);
Related
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...
I have declared socket.io in index.js file, And I would pass soket object to route module.
const express = require('express');
const app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var MongoClient = require('mongodb').MongoClient;
var server = require('http').Server(app);
var io = require('socket.io')(server);
var routes = require('./routes/routes')(io);
const dbb = mongoose.connect("mongodb://xxx:xxx#ds137600.mlab.com:37600/tasksdb");
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
app.use('/', routes);
var server= app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
routes.js
var express = require("express"); // call express
var taskSchema = require("../models/taskModel");
var mongoose = require("mongoose");
var router = express.Router(); // get an instance of the express Router
router
.route("/tasks")
.post(function (req, res, next) {
....
});
router
.route("/tasks")
.get(function (req, res) {
....
});
module.exports = router;
How can I transfert it to routes.js? what are the different ways to do it ? I still not well understanding how modules works
For server:
const app = express();
app.use(logger('tiny'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use((req, res, next) => {
const origin = req.headers.origin;
if (allowed_header.indexOf(origin) > -1) {
res.header('Access-Control-Allow-Origin', origin);
}
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, gutsyJwt, Accept'
);
next();
});
app.io = require('socket.io')({
origins: ['*:*'],
});
require('./routes')(app);
module.exports = app;
Then in route:
module.exports = app => {
app.post('/api/bar', (req, res) =>
fooController.bar(req, res, app.io)
);
};
Then in controller:
module.exports = {
bar(req, res, io) {
io.emit('message', req.body.message);
res.status(200).send({msg: 'Message broadcasted!'});
},
};
In this post, it is asking the similar question as well if you need more reference.
ExpressJS how do I pass objects with state (eg. connections)?
I have this router (http/api/ping.js):
var express = require('express');
var router = express.Router();
router.get('/ping', function (req, res) {
res.send("You called /api/ping");
});
module.exports = router;
This router is embedded into this router (http/api/index.js):
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.send('You called /api');
});
router.use('/ping', require('./ping'));
module.exports = router;
And this router is used by my Express.js app (app.js):
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('./config').logger;
// Create app
var app = express();
var server = http.createServer(app)
var io = require('socket.io')(server);
// App config
app.use(bodyParser.json());
app.use('/api', require('./http/api'));
// Display requests on console
app.use(function (req, res, next) {
logger.trace(req.method, req._parsedUrl.href);
next()
});
module.exports = {
app: app,
server: server
};
When I run the app, /api returns You called /api, but /api/ping gives me a 404.
I am using Node 6.9.1 and Express ^4.14.0
I think order matters in this scenario. Try putting /ping above the / get route.
router.use('/ping', require('./ping'));
router.get('/', function (req, res) {
res.send('You called /api');
});
Also in your ping route you say the path to your route is /ping you also say it is /ping when you import it to the other router, which would make the path /api/ping/ping
change
router.get('/ping', function (req, res) {
res.send("You called /api/ping");
});
to
router.get('/', function (req, res) {
res.send("You called /api/ping");
});
I think your routing is incorrect on this line
router.use('/ping', require('./ping'));
this will point to http/api/ping/ping
it should be
router.use('/', require('./ping'));
How start app in express js (nodejs)? TypeError:app.set is not a function.
Console.log screen
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
});
Solved a problem:
1. add module.exports = app;
Taking the following basic Express: 'Hello World' example as my starting point:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('App listening at http://%s:%s', host, port);
});
I'm trying to organize the code in different .js files to separate configuration and routing.
This way I would have app.js:
var express = require('express');
var app = express();
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('App listening at http://%s:%s', host, port);
});
// Expose app
exports = module.exports = app;
and /routes/api.js (having api.js inside a child directory called routes):
var app = require('../app.js');
app.get('/', function (req, res) {
res.send('Hello World!');
});
but exports = module.exports = app; and var app = require('../app.js'); are not working: I get the message Cannot GET / all the time when calling the API method.
you should make app.js your 'main' file, and the routes should be inclulded in it.
your route file should look somthing like this:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.send('Hello World!');
});
module.exports = router;
and to your app.js add:
var api = require("./routes/api.js");
...
//all your code for creating app
...
app.use('/', api);