socket.io not found when calling server - javascript

I'm trying to connect socket.io on Angular and Nodejs server
In Angular I have declared a new socket and connect it
import * as io from 'socket.io-client';
...
#component
...
const socket = io.connect('http://localhost:3000');
In back end : server.js
const express = require('express');
const app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.set('origins', 'http://localhost:4200');
var routes = require('./routes/routes')(io);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:4200");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT ,DELETE");
res.header('Access-Control-Allow-Credentials', true);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
console.log("connectd");
});
app.use('/', routes);
var server = app.listen(3000, function (io) {
})
The app is compiling and getting data from server. but only socket.io is not working
I get this error:
GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MEpN9Qy 404 (Not Found)

socket.io is attached to http:
var http = require('http').Server(app);
var io = require('socket.io')(http);
so you have to use:
http.listen(3000)
instead of
app.listen(3000) // This will only start an express server
Your socket server never starts, that's why you're getting a 404, since only express is running.

Related

Can't display request.body in server log?

I'm new to Node and I can't seem to get my request to complete. I'm just trying to create a basic handshake between server and client by sending the location for the client to the server and displaying that into the server log. I'm not sure why I can't display the data into the log.
Index.js
const express = require('express');
const app = express();
app.listen(8080, () => console.log('listening at 8080'));
app.use(express.static('public'));
app.use(express.json({limit: '1mb'}));
app.post('/api',(request,response) => {
console.log('I got a request!');
console.log(request.body);
});
Index.html
<script>
if('geolocation' in navigator) {
console.log('geolocation is avaliable');
navigator.geolocation.getCurrentPosition(async position => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
console.log(lat,lon);
document.getElementById('latitude').textContent = lat;
document.getElementById('longitude').textContent = lon;
const data = {lat, lon};
const options = {
method: 'POST',
header:{
'Content-Type':'application/json'
},
body: JSON.stringify(data)
};
fetch('/api',options);
});
} else{
console.log('geolocation is not avaliable');
}
</script>
Some things to note. The request does seem to complete and no errors are shown in the developer console.
Server information:
-[nodemon] restarting due to changes...
-[nodemon] starting node index.js
-listening at 8080
-I got a request!
-{}
Add the following to your index.js:
npm i -S body-parser
// Takes the raw requests and turns them into usable properties on req.body
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/api', (request, response) => {
console.log('I got a request!');
console.log(JSON.stringify(request.body));
});
Try the following code in your index.js
const express = require('express')
const app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*")
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET')
}
next();
});

getting "Cannot GET /public/signup.html" error in express js

Very new to express and file system and don't have much idea about directories so getting this error.
var express= require('express');
var path= require('path');
var mysql= require('mysql');
var bodyParser= require('body-parser');
var app= express();
app.get('/', function(req, res) {
res.set( {
'Access-control-Allow-Origin': '*'
});
return res.redirect('/public/signup.html');
}).listen(2121);
console.log('server Running on : 2121');
app.use('/public',express.static(__dirname +"/public"));
Getting error "Cannot GET /public/signup.html"
My directories is:
-Express
--Server.js
--public
---signup.html
Looks like your code is a little jumbled up. Separate out your port listener - this should always come last. Add your routes and middleware before that as individual calls to app, and also register your get request to redirect back to your server to the signup html.
This should work:
var express = require("express");
var path = require("path");
var port = 2121;
var app = express();
// Register Middlewares/Headers
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
next();
});
// Register Static
app.use("/public", express.static(__dirname + "/public"));
// Register redirect
app.get('/', (req, res) => {
res.redirect(req.baseUrl + '/public/signup.html');
});
app.listen(port, () => {
console.log("server Running on : ", port);
});
You're calling listen on app before you call use on your middleware and there are a few mistakes in your code. I think this should work:
app
.use('/public',express.static(`${__dirname}/public`))
.get('/', (req, res) => {
res.header({
'Access-control-Allow-Origin': '*'
});
res.redirect(`${req.baseUrl}/public/signup.html`);
})
.listen(2121);
You should provide
app.use('/public',express.static(__dirname +"/public"));
Before you using app.get
Full example:
var express= require('express');
var path= require('path');
var mysql= require('mysql');
var bodyParser= require('body-parser');
var app= express();
app.use('/public',express.static(__dirname +"/public"));
app.get('/', function(req, res) {
res.set( {
'Access-control-Allow-Origin': '*'
});
return res.redirect('/public/signup.html');
}).listen(2121);
console.log('server Running on : 2121');

Socket.IO & SSL

i activated HTTPS and Socket.IO returned error:
net::ERR_CONNECTION_REFUSED
Server.js:
var fs = require('fs');
var https = require('https');
var options = {
key: fs.readFileSync(‘./cert.pem'),
cert: fs.readFileSync(‘./cert.crt')
};
var express = require('express'),
app = express(),
server = https.createServer(options, app);
var io = require('socket.io').listen(server);
server.listen(8080);
Front:
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
var socket = io.connect('IP:8080');
If deactivated HTTPS, Socket.IO worked...
two theories:
1) Are you hosting this remotely? If so, you may not have the same port number as your local server. For instance, on Heroku hosted node apps, you can access the port number with:
process.env.PORT
So you could do:
server.listen(process.env.PORT || 8080);
2) It may also be a CORS issue. You will need to include access-control-allow-origin headers. Include a middleware utility like the following between setting up 'app' and calling 'server.listen(...)':
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
if ('OPTIONS' == req.method) {
res.writeHead(200);
res.end();
} else {
next();
}
});
Hope this helps

Express.js 'socket.io/socket.io.js 404'

I'm trying to incorporate a live user count on my website http://clickthebutton.herokuapp.com which uses Express JS. When trying to install socket.io I get this error:
GET /socket.io/socket.io.js 404 1.911 ms - 1091
Yes, I have used 'npm install socket.io --save'
I have looked around for answers, tried them and nothing has helped. If anyone thinks they know what's happening, a response would be well appreciated! Here's my code:
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var io = require('socket.io')(app);
var routes = require('./routes/index');
var users = require('./routes/users');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var server = app.listen(app.get('port'), function () {
console.log('server listening on port ' + server.address().port);
})
var io = require('socket.io').listen(server);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
index.ejs
<!-- socket.io -->
<script src="socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect();
</script>
</div>
</center>
</body>
routes/index.js
var express = require('express');
var router = express.Router();
var redis = require('redis'), client = redis.createClient(secret, "secret"); client.auth("secret", function() {console.log("Connected!");});
var app = express();
var server = require('http').Server(app);
var http = require('http');
var io = require('socket.io').listen(server);
io.on('connection', function(socket){
console.log('a user connected');
console.log(Object.keys(io.sockets.connected));
});
io.on('connection', function (socket) {
console.log('Socket.io connected!')
});
I only copy/pasted the code that referenced socket.io
Thanks!
In app.js alone you're creating three instances of socket.io, and once again in routes/index.js. There should be only one throughout your entire app.
A common setup for Express looks like this:
var app = require('express')();
var server = app.listen(app.get('port'), function () {
console.log('server listening on port ' + server.address().port);
});
var io = require('socket.io')(server);
If you need to reference either app, server or io in other files, you need to pass it as a variable.
EDIT: because you're using an express-generator based setup, the HTTP server will be created in bin/www and not app.js. In that case, you also need to create the socket.io server there:
/**
* Create HTTP server.
*/
var server = http.createServer(app);
var io = require('socket.io')(server); // add this line
Again, if you need to reference io somewhere else in your codebase, you need to pass it along from there.

Node.js freeze after a few requests

I am trying around with nodejs and socket.io
But my application refuses to work after a few requests. It takes a while and after some time it starts working again.
Here is the code for the nodejs-server, where i expect the issue.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('db.sqlite');
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 8080;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var router = express.Router();
router.post('/', function (req, res) {
res.sendFile(__dirname + "/app/index.html");
});
router.get('/sample', function (req, res) {
res.sendFile(__dirname + "/app/sample.html");
});
router.post('/api/error', function (req, res) {
var data = req.body;
data.date = Date();
io.emit('error', JSON.stringify(data));
res.header("Access-Control-Allow-Origin", "*");
});
io.on('connection', function(socket){
console.log('a client connected');
});
app.use('', router);
app.use(express.static('app'));
app.use('/static', express.static('node_modules'));
// START THE SERVER
server.listen(port);
console.log('Magic happens on port ' + port);
The applikation is for monitoring errors in a full webstack.
The handler for POST /api/error isn't sending back a response, so the client will continue to wait. At some point, it may decide not to open any more connections to the server until the previous ones have been answered (or have timed out).
You can just send back a 200 response:
router.post('/api/error', function (req, res) {
var data = req.body;
data.date = Date();
io.emit('error', JSON.stringify(data));
res.header("Access-Control-Allow-Origin", "*").sendStatus(200);
});

Categories

Resources