I'm trying to use gun in an express/node project, however I want to mount the endpoint as /db. I had hoped the following code would work but keep getting a Route.get() requires callback functions error:
var express = require('express');
var Gun = require('gun');
var app = express();
var port = 8080;
var gun = new Gun({
file: './data.json'
});
// mount the gun db server
app.get('/db', gun.router);
// regular express route
app.get('/', function(req, res) {
res.send('other stuff...');
});
// start the server
app.listen(port, function () {
console.log('Web server listening on port ' + port);
});
Any suggestions?
Doherty!
GUN can be used with express, but it is not an express route. For example, lets first go over a simple gun server mounted with express:
var express = require('express');
var Gun = require('gun');
var app = express();
app.use(Gun.serve).use(express.static(__dirname));
var server = app.listen(80);
Gun({file: 'data.json', web: server});
( https://github.com/amark/gun/blob/master/examples/express.js )
GUN's API is now available in the browser at:
<script src="http://YOURSERVER.com/gun.js"></script>
<script>
var gun = Gun('http://YOURSERVER.com/gun');
gun.get('key').get('hello').put('world!');
gun.get('key').get('hello').on(function(data){ console.log(data) });
</script>
GUN is not available as an express route. For example, this does not work:
http://YOURSERVER.com/data/key/hello?put=world!
Why?
GUN is a realtime database, if you use a REST or CRUD routes with express as its API, then you lose the realtime capabilities. Meaning you would have to write your own custom long-polling implementation, which defeats the point of having an express route.
I understand, but I still want a REST or CRUD API for GUN?
It should not be hard to create an HTTP route that proxies gun. Here is some pseudocode that should help get you started. If you build it, please make it an Open Source module on NPM so others can enjoy it!!!
// this is pseudocode!!!
app.get('/data', (req, res) => {
path(req).val(data => res.send(data))
});
app.put('/data', (req, res) => {
path(req).put(req.param.put, ack => {
res.ack? 0 : res.ack = res.send(ack)
})
});
var path = (req) => {
var ref = gun;
req.path.split('/').forEach(key => ref = ref.get(key));
return ref;
}
Let us know if you build it! As always, the community chatroom is friendly and active. Ask for help there, and ask questions here. Thanks for making this a SO question!
Related
On my debian server, I installed node and then started node server on port 3000. The server is running, but it isn't visible from the browser
Now when I try to get it running via my domain or via my ip(for example xx.xxx.xx.xx:3000) or my domain (my-domain.com:3000) in both cases it doesn't work. I think I don't quite get the concept and I tried to search for a billion different things, but I can't find the solution to my problem. Could someone tell me, if I need to setup something else, too?
My server js code is
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);
server.listen(3000, () => {
console.log('listening on *:3000');
});
io.on('connection', function (socket) {
socket.on( 'new_message', function( data ) {
io.sockets.emit( 'new_message', {
message: data.message,
date: data.date,
msgcount: data.msgcount
});
});
});
Error i got
You need to listen for GET requests in order to respond to them.
Try adding something like:
app.get('/', function (req, res) {
res.send('GET request test.')
})
In your case make sure you add the route before passing the app to the http.createServer() method, or otherwise just use something like app.listen(3000).
More info in the docs: https://expressjs.com/en/guide/routing.html
why are you using express and http both packages.
you can run server by either of them.
and then add a get route for it.
import { createServer } from "http";
import { Server } from "socket.io";
const httpServer = createServer();
const io = new Server(httpServer, {
// ...
});
io.on("connection", (socket) => {
// ...
});
httpServer.listen(3000);
I hope this will work!
I am on the process of building a chat application with nodejs, reactjs mongo and socket.io.My chat app consists of both one to one and group chats.I have built a schema for group chat and i am inserting group names along with its members and their chats in the table.Since im a beginner towards socket.io, I dont know where to put the socket logic that needs to be fired after the db post operation.Can some one suggest any examples for me?
Update your code accordingly:
=> server.js file
// Declare socket.io
const io = require('socket.io')(server);
// Add middleware to set socket.io in
app.use((req, res, next)=>{ res.locals['socketio'] = io; next(); });
=> In your controller file
// Get the value of socket.io
module.exports = your_function_name = (req, res) => {
const io = res.locals['socketio']
// Use io when you need.
});
Hope this solves your query.
You can separate you socket related code by following way :
==>app.js
var express = require('express');
var socket = require('./socketServer');
var app = express();
var server = app.listen((config.node_port || 3000), function () {
console.log('Listening on port ' + (config.node_port || 3000) + '...');
});
socket.socketStartUp(server);
module.exports = app;
==>socketServer.js
var io = require('socket.io')();
var socketFunction = {}
socketFunction.socketStartUp = function (server) {
io.attach(server);
io.on('connection', function (socket) {
console.log("New user is connected with socket:", socket.id);
})
}
module.exports = socketFunction;
You can also check node API startup code with socket functionality in below link:
Node API Start up
Hope this answer is helpful to you
I am still learning nodejs and was listening to daniel shiffman's video on how to setup the twitter api and how to get data from it.
Now, the code was working and I was getting back data, but it was all happening in the terminal.
What I wanted to do was to show the twitter data in my browser and wasnt sure how to do that. I tried searching for it, but didnt get much help.
So, I just tried doing whatever I knew and it worked and therefore I am still not sure that the code I have written is the proper way to do this.
I'd love to know if there's a mistake somewhere or If there's some other way I should have done this.
Anyways, here's the code
var http = require('http');
var express = require('express');
var app = express();
var port = 8080; // Use 8080 for local development because you might already have apache running on 80
console.log('The bot is starting');
var Twit = require('twit');
var config = require('./config');
console.log(config);
var T = new Twit(config);
var params ={
q:'spider',
count:5
}
T.get('search/tweets', params, gotData);
function gotData(err, data, response) {
var tweets = data.statuses;
app.get('/',function(req,res){
req=params;
var tweetz='';
for(var i=0;i<tweets.length;i++){
console.log(tweets[i].text+'================================');
tweetz = '<p>'+ tweetz+tweets[i].text+'</p>';
}
res.send(tweetz);
});
}
app.listen(port, function () {
console.log(`app listening on port ${port}!`);
});
The mistake you are doing is declaring app.get inside the callback.
app.get("/", function....) is a route which responds to GET requests which means whenever a user requests for "/", the callback which is the function(req, res) is called.
So the code should be:
app.get("/", function(req, res) {
// User requested for "/" route, now get tweets
T.get('search/tweets', params, function(err, data) {
//Tweets received, now send the tweets to the user
var tweets = data.statuses;
return res.send(tweets);
})
})
Then go to http://localhost:8080/ and it should work.
I have an express server, and while building it created several "helper" functions on their own routes. I'd like those routes to be accessed on a different port. Is there anyway to do this in express?
In the code below, the "/factory" route (and other functionality) would be on one port, and the helper routes of "/killallthings", "/listallthings", and "/killserver" would be on a separate port.
Here is a simplified version of the code:
var express = require('express');
var things = [];
var app = express();
var port = 8080;
app.post('/factory/', function(req, res) {
//Create a thing and add it to the thing array
});
//Assume more functions to do to things here....
app.post('/killallthings/', function(req, res) {
//Destroy all the things in the array
});
app.post('/listallthings/', function(req, res) {
// Return a list of all the things
});
app.post('/killserver/', function(req,res){
//Kills the server after killing the things and doing clean up
});
//Assume https options properly setup.
var server = require('https').createServer(options, app);
server.listen(port, function() {
logger.writeLog('Listening on port ' + port);
});
Is this possible with express?
Based on Explosion Pills suggestion above, I modified the code in roughly this way:
var express = require('express');
var things = [];
var app = express();
var admin_app = express();
var port = 8080;
var admin_port = 8081;
app.post('/factory/', function(req, res) {
//Create a thing and add it to the thing array
});
//Assume more functions to do to things here....
admin_app.post('/killallthings/', function(req, res) {
//Destroy all the things in the array
});
admin_app.post('/listallthings/', function(req, res) {
// Return a list of all the things
});
admin_app.post('/killserver/', function(req,res){
//Kills the server after killing the things and doing clean up
});
//Assume https options properly setup.
var server = require('https').createServer(options, app);
server.listen(port, function() {
logger.writeLog('Listening on port ' + port);
});
var admin_server = require('https').createServer(options, admin_app);
admin_server.listen(admin_port, function() {
logger.writeLog('Listening on admin port ' + admin_port);
});
I wish I knew how to give Explosion Pills the credit for the answer! :)
If you are trying to create multiple servers then why not crate multiple bin/www files with different ports and configurations. Another way could be pass port number directly from command line.
I'm actually working on a little project, where i'm supposed to recreate a drawing multiplayer game with node.js, mongoDB, socket.io and canvas.
The drawer is working like a charm, and the server seems to work well too. I got my register/login/sessions and database up and working, the only problem is socket.io. When an user is joining the game room, he can see the drawer and tools, but no connection. Why ? The browser can't find socket.io.js.
What I did :
I verified if it was installed, it is with npm install socket.io.
I checked if the server was starting it when turning the server on : Got "socket.io started" in my console.
I checked my HTML code, here it is :
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
According to the billions of tutorials/dev sites/help subjects, this is supposed to work. But it's not. When opening the console of my browser, I got this :
X GET http://localhost:1337/socket.io/socket.io.js NOT FOUND.
I don't know where is the problem, I can't figure this out and it's giving me a huge headache.. So I'm here.
Thanks in advance for helping ! :)
Given the code in your comment, you're not using the correct variable for initializing socket.io.
Try this:
var express = require('express');
var app = express();
var server = app.listen(1337);
var io = require('socket.io').listen(server);
...
So instead of having socket.io 'listen' on the Express app instance, it should listen to what app.listen(...) returns (which happens to be an http.Server instance).
For anyone landing here because they're going through the v4.x socket.io get started example, all you need to do is add another endpoint to your index.js file
index.js
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);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// add this
app.get('/socket.io/socket.io.js', (req, res) => {
res.sendFile(__dirname + '/node_modules/socket.io/client-dist/socket.io.js');
});
///
io.on('connection', (socket) => {
console.log('a user connected');
});
server.listen(3000, () => {
console.log('listening on *:3000');
});