I've got a simple app which uses socket.io module for node.js.
When i run my server with node express_server.js command it works ok, but when i want to open my http://localhost:8080 page in browser, node throws an error:
/home/tomek/dev/node/node_modules/express/lib/application.js:119
this._router.handle(req, res, function(err) {
^
TypeError: Cannot read property 'handle' of undefined
at Function.app.handle (/home/tomek/dev/node/node_modules/express/lib/application.js:119:15)
at Server.app (/home/tomek/dev/node/node_modules/express/lib/express.js:28:9)
at Manager.handleRequest (/home/tomek/dev/node/node_modules/socket.io/lib/manager.js:565:28)
at Server.<anonymous> (/home/tomek/dev/node/node_modules/socket.io/lib/manager.js:119:10)
at Server.EventEmitter.emit (events.js:110:17)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:504:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:111:23)
at Socket.socketOnData (_http_server.js:357:22)
at Socket.EventEmitter.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:156:16)
My express_server.js file looks like:
var express = require('express'),
socket = require('socket.io'),
http = require ('http');
var app = express();
server = http.createServer(app);
server.listen(8080);
var io = socket.listen(server);
io.sockets.on('connection', function (client) {
console.log('-- Client connected --');
});
and index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chat application</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var server = io.connect('http://localhost:8080');
</script>
</body>
</html>
There is no router defined. Try add this after creating the app (var app = express()):
app.get('/', function(req, res) {
// res.send('hello world');
res.sendfile('index.html');
});
Express is a framework that amongst other stuff replaces the 'http' module. You appear to be trying to use both together. Try this:
var express = require('express'),
var app = express();
app.get('/', function(req, res) {
res.sendfile('index.html');
});
var port = Number(process.env.PORT || 8080);
app.listen(port, function() {
console.log("Listening on " + port);
});
Credit to Ben for the nudge on the get method.
Related
I am trying to set up a simple node.js server to do some basic Socket.io work but when I try to serve my Static JS files I get this error:
GET https://somewebsitewithfiles.website net::ERR_ABORTED 404
Here is my server and local code:
Server:
var express = require('express');
var app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/HTML/index.html');
});
app.use(express.static('Static'))
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
})
Local:
<!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="/Static/User.js"></script>
</body>
</html>
As you can see I have used the express static file command witch doesnt seem to be working . My file system consists of my project folder and inside that is my Server JS file. There is also folder in there called "Static" that has has my static files and a folder called HTML that has my index.html
any help appreciated. Thanks
app.use(express.static('Static'))
try putting this line above your '/' route
code:
var express = require('express');
var app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.use(express.static('Static'))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/HTML/index.html');
});
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
})
Edit:
<script src="/Static/User.js"></script>
You dont have to mention the 'static' in the src path.
Correct way:
<script src="/User.js"></script>
I'm trying to write a simple client server application.
That's the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<script src="client.js"></script>
</body>
</html>
server.js file:
const express = require('express');
const app = express();
const port = 3000;
const server = app.listen(port);
const io = require('socket.io')(server);
app.get('/', (req, res) => {
res.send('Hello World!');
});
io.on('connection', (socket) => {
console.log('a user connected');
});
client.js file:
const socket = io('https://localhost:3000/');
At this moment if I start the server by typing node server on the terminal and I open the HTML file using the LiveServer vs extension, the console doesn't show the text a user connected, it also returns an error which is:
GET
https://localhost:3000/socket.io/?EIO=4&transport=polling&t=NdZ4wOd
net::ERR_SSL_PROTOCOL_ERROR
I don't know what I'm doing wrong.
In the client.js file you could try const socket = io.connect(); and I'm not sure but i think <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script> Should be in the header but i could be wrong about that.
**Make Changes In Your Server File **
const express = require('express');
const cors = require('cors');
const app = express();
const port = 3000;
app.use(cors());
const server = app.listen(port);
const io = require('socket.io')(server);
app.get('/', (req, res) => {
res.send('Hello World!');
});
io.on('connection', (socket) => {
console.log('a user connected');
});
Install cors npm package before starting your server using npm i cors
i try to create simple express apllication serv.js:
var express = require('express'),
app = express();
app.listen(3000, function() {
console.log('Server is running');
});
and when i run it node serv.js, i've got error:
/home/leonid/proj/first/node_modules/express/lib/application.js:119
this._router.handle(req, res, function(err) {
^
TypeError: Cannot call method 'handle' of undefined
at Function.app.handle (/home/leonid/proj/first/node_modules/express/lib/application.js:119:16)
at Server.app (/home/leonid/proj/first/node_modules/express/lib/express.js:28:9)
at Server.EventEmitter.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2108:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
at Socket.socket.ondata (http.js:1966:22)
at TCP.onread (net.js:527:27)
How can it resolve?
You have to define a route for the server to respond to requests.
var express = require('express'),
app = express();
app.get('/hello.txt', function(req, res){
res.send('Hello World');
});
app.listen(3000, function() {
console.log('Server is running');
});
Doesn't work anyway, I really tried so many different ways but nothing works..
I want establish a realtime connection with socket.io to monitor a redis db to get every new added item on a list.
Any ideas ?
app.js
/**
* Module dependencies.
*/
var express = require('express');
var http = require('http');
var path = require('path');
var crawler = require('crawler.js');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
//app.use(express.errorHandler());
}
app.get('/rootaccess',function(req, res){
res.render('crawlercontrol');
});
app.get('/crawler/monitor',function(req, res){
res.render('monitor');
});
app.get('/crawler/start',function(req,res){
crawler.start(res);
});
app.get('/crawler/stop',function(req,res){
crawler.stop(res);
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var io = require('socket.io').listen(app.listen(3111));
io.sockets.on('connection', function (socket) {
console.log('hei socket.io');
socket.emit('message', { message: 'welcome to the chat' });
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>ROOT Monitor</title>
<link rel="stylesheet" href="/css/normalize.css">
<link rel="stylesheet" href="/css/foundation.css" />
<link rel="stylesheet" href="/css/font-awesome.min.css">
<script src="/js/libs/modernizr.js"></script>
</head>
<body>
<div id="monitor">
Monitor
</div>
</body>
<script src="/js/libs/jquery-1.10.2.js"></script>
<script src="/js/libs/foundation.min.js"></script>
<script src='/socket.io/socket.io.js' />
<script>
var socket = io.connect('http://localhost:3111');
socket.on('news', function (data) {
console.log(data);
});
</script>
</script>
</html>
At this moment the only Error which appears is that socket.io doesn't provide the socket.io.js for the client..
I don't know if this is it or not; it's just a hunch. In app.js you tell the express app to listen on the assigned port in the app object:
http.createServer(app).listen(app.get('port'), ...
But then when you create io, you call app.listen() again within the listen method of the object require returns.
var io = require('socket.io').listen(app.listen(3111));
My hunch is that perhaps you are forcing the app server to listen twice which may be causing the issue, again just a hunch. If I am wrong tell me. If you really want to listen on port 3111, you could try this:
var io = require('socket.io').listen(3111);
See if that gets you anywhere.
Environment
Express 3.2.4
ShareJS 0.6.2
OS X 10.8.3
Goal
I am trying to get ShareJS running inside of an Express app.
Problem
I get the following error on running node app.js:
/Users/eric/Documents/Projects/collabit/node_modules/share/src/server/index.coffee:52
server.use(options.staticpath, connect["static"]("" + __dirname + "/../.
^
TypeError: Object #<Server> has no method 'use'
at Function.create.attach.attach (/Users/eric/Documents/Projects/collabit/node_modules/share/src/server/index.coffee:52:14)
at Object.<anonymous> (/Users/eric/Documents/Projects/collabit/app.js:43:16)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
I used the express cli interface to generate an app and was working with SocketIO just fine before deciding to swap in ShareJS. I'm pretty sure my issue is how I'm crafting the server but I don't know enough to figure out how I should be creating the server object to keep the express functionality but allow ShareJS to attach.b
Code
/**
* Module dependencies.
*/
var express = require('express')
, sharejs = require('share')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
/**
* ShareJS Code
*/
var options = {db: {type: 'none'}};
sharejs.server.attach(server, options);
Question
What is the proper way to create my server object in order to allow ShareJS to attach to it while retaining the Express functionality.
Thanks!
Thanks in advance for help and let me know if any additional information is needed.
I had a similar issue. After a lot of trial and error this worked for me:
var express = require('express'),
http = require('http'),
sharejs = require('share').server;
var app = express();
var server = http.createServer(app);
var options = {db:{type:'none'}}; // See docs for options. {type: 'redis'} to enable persistance.
// Attach the sharejs REST and Socket.io interfaces to the server
sharejs.attach(app, options);
app.use(app.router);
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
server.listen(8000, function () {
console.log('Server running at http://127.0.0.1:8000/');
});
app.get('/', function(req, res) {
res.render('share.html');
});
Then in views/share.html I had the standard example html:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://ajaxorg.github.com/ace/build/src/ace.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="/channel/bcsocket.js"></script>
<script src="/share/share.js"></script>
<script src="/share/ace.js"></script>
<script>
$(document).ready(function() {
var editor = ace.edit("editor");
sharejs.open('hello', 'text', 'http://localhost:8000/channel', function (error, doc) {
doc.attach_ace(editor);
});
});
</script>
<style>
#editor {
width: 200px;
height: 100px;
}
</style>
</head>
<body>
<div id="editor"></div>
</body>
</html>