connect a postgresql database in node js - node.js

Here is my code:
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.get('/js/client_world.js', function(req, res){
res.sendFile(__dirname + '/js/client_world.js');
});
io.on('connection', function(socket){
console.log("A user is connected");
socket.on('disconnect', function(){
console.log("User disconnected");
});
});
http.listen(3000, function(){
console.log("Listenng to port 3000")
});
index.html:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="/socket.io/socket.io.js"></script>
<script src="//threejs.org/build/three.min.js"></script>
<script src="/js/client_world.js"></script>
</head>
<body>
<div id="container"></div>
<script>
var socket = io();
socket.on('connect', function(){
loadWorld();
});
</script>
</body>
</html>
and a third file, client_world,js, where I want to read data from a database.
The first line
var {Pool,Client} = require('pg');
causes an error.
Is this way to access the DB wrong? Thanks in advance for a hint.

Related

Client not connecting when using socket.io

I don't know what I'm missing. No error is thrown or anything, it just doesn't connect.
Server side code
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
// Run when client connects
io.sockets.on('connection', socket => {
console.log('New Conncection...')
})
const PORT = 4000 || process.env.PORT;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Client Side Code
var io = require('socket.io-client')
var socket = io.connect('http://localhost:4000', {reconnect: true});
Here is a simple working example:
File structure:
.
├── public
│ └── index.html
└── server.js
server.js:
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
// Run when client connects
io.sockets.on('connection', (socket) => {
console.log('New Conncection...');
io.sockets.emit('event', 'everyone');
socket.on('disconnect', () => {
console.log('disconnected');
});
});
const PORT = 4000 || process.env.PORT;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/socket.io-client#2/dist/socket.io.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
var socket = io('http://localhost:4000', { reconnection: true });
socket.on('connect', function() {
console.log('socket connection success');
});
socket.on('event', function(data) {
console.log('data:', data);
});
socket.on('disconnect', function() {
console.log('socket disconnect');
});
});
</script>
</body>
</html>
The logs for server-side:
Server running on port 4000
New Conncection...
disconnected
New Conncection...
The logs for client-side:
socket connection success
data: everyone

connection between client-side and server-side not working on socket.io

I have problem with socket connection between client-side and server-side .
I have this code on server-side :-
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket) {
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
and this code on client-side :-
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.1/socket.io.js"></script>
<script>
var socket = io();
</script>
</body>
</html>
the code in server-side is working , but in client-side i have these errors :-
can anyone help me to fix problem ?
Thanks a lot :(
Its looks like you are opening file directly into browser. Actually you are not specify path for serving your html. so that socketio can POST and poll data there.
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
If you really need to open file directly into browser rather than serving via nodejs on same port you have to specify host and port in client-side socket.
rather than simply using io() which will look for local port you can use this
var socket = io("http://localhost:3000");
So here how it works for me
// server
const app = require('express')();
const http = require('http').createServer(app);
// ^^^^^^^^^^^^
const io = require('socket.io')(http);
// here you should serve your index.html file
// and the socket io will know which socket to track
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
// client/index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<script src="/socket.io/socket.io.js"></script>
<script>
// here it automatically track localhost:3000
var socket = io();
</script>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
Hope it will help you

net::ERR_CONNECTION_REFUSED socket.io

i'm trying to have a socket working on my sever
here is my app.js file
console.log('app.js says hi');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.use(express.static(__dirname + '/bower_components'));
app.get('/', function(req, res,next) {
res.sendFile(__dirname + '/index.html');
});
server.listen(4200);
and my index.html file
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<h1>Hello World!</h1>
<div id="future"></div>
<form id="form" id="chat_form">
<input id="chat_input" type="text">
<input type="submit" value="Send">
</form>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:4200');
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
});
</script>
</body>
</html>
and in the console log I get this error:
GET http://localhost:4200/socket.io/?EIO=3&transport=polling&t=LsOF2yq net::ERR_CONNECTION_REFUSED
i found it
replace this line
var socket = io.connect('http://localhost:4200');
with
var socket = io.connect('http://yourdomain.com:4200');

Moving socket.io into controller

This is my app structure
controller
routes.js
public
jquery.js
socket.io.js
app.js
index.html
The app.js file contains the socket program which emits the some message when user connects. Now the problem was how I emit the message from routes.
My nodejs code was below:
This is my app.js file code:
var express=require('express');
var app=express();
var server=require('http').createServer(app);
var io=require('socket.io').listen(server);
app.use('/', express.static(__dirname + '/'));
io.sockets.on('connection',function(socket){
socket.emit('message',{msg:'hai'});
});
app.use('/cal',require('./controllers/route'));
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
server.listen(3000);
This is my route.js code:
var express=require('express');
var route=express.Router();
route.get('/',function(req,res){
//socket.emit('message',{msg:'hai'});
});
module.exports=route;
This is my index.html file code:
<htmL>
<head>
<title>Chat with socket.io and node.js</title>
</head>
<body>
<script src="./public/jquery.min.js"></script>
<script src="./public/socket.io.js"></script>
<script>
jQuery(function($){
var socket = io.connect();
socket.on('message',function(data){
alert(data.msg);
});
});
</script>
</body>
</html>
Thank You.
Routes has nothing to do with sockets. You have to listen on sockets, not on routes. Here's par of the docs (http://socket.io/docs/) for using Socket.IO with Express:
// server - app.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
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);
});
});
// client - index.js
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>

socket node.js express 404 error

From a simple chat example at https://github.com/guille/chat-example/blob/master/index.js
For information, I'm not serving html file through following code, either the html is going to be embedded inside this iphone app or hosted somewhere. Question is how to connect the html to the nodejs environment where the sockets will be handled or is it a must that the html goes through the res.sendfile statement?
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
html
<script src="js/api/jquery-2.1.1.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
var socket = io();
socket.emit('chat message', "hello world");
});
</script>
I'm getting a 404 error, attached screenshot
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log(msg);
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
You are using res.sendfile when it should be res.sendFile (capital F)

Resources