Connect is not a function Node.js - javascript

I am trying to export Connectas an middleware for an HTTP server test, but when I execute the code, it says the follow :
connect.createServer is not a function
My code :
hello_world.js
function helloWorld(req, res) {
res.end('Hello World!');
}
module.exports = helloWorld;
hello_world_app (where the problem is) :
var connect = require('connect');
// import middlewares
var helloWorld = require('./hello_world');
var app = connect.createServer(helloWorld);
app.listen(8080);
He points out to the hello_world_app in the var app, saying that is not a function. How can I make this work ?

Looking at the docs for connect https://www.npmjs.com/package/connect - You are using it incorrectly
You would want something like this:
var connect = require('connect');
var helloWorld = require('./hello_world');
var http = require('http');
var app = connect();
app.use(helloWorld);
http.createServer(app).listen(8080);
Connect doesn't have a function called createServer which is why your code is erroring, that function exists in the http module.

You still need to create the http server with server with the http module. The 'connect' library just helps you use middleware more easily, so you have to plug the middleware into that.
var connect = require('connect');
// import middlewares
var helloWorld = require('./hello_world');
// Initiate the framework
var app = connect();
// Plug in your middleware
app.use(helloWorld);
// Tell http to use the framework
http.createServer(app).listen(8080);

The connect documentation states that you use it this way:
var connect = require('connect');
var http = require('http');
var app = connect();
http.createServer(app).listen(3000);
https://www.npmjs.com/package/connect

Related

Nodejs using multiple files to catch events

I was wondering if it was possible to use multiple files on nodeJS that will catch events and handle them?
For example right now I have a server.js which is filled with code to handle chats and chatrooms.
Which would briefly just look as follow
var fs = require( 'fs' );
var app = require('express')();
var https = require('https');
server.listen(1234);
io.on('connection', function(client){
client.on('room_join', function(roomId){(
client.join(roomId);
});
client.on('message', function(data){
io.to(data.roomId).emit('message', {message: data.message});
});
});
Now what I would prefer if possible, is to create a messages.js, and rooms.js file that will handle this. But I would actually prefer those catching the events aswell. So my rooms.js file would look something like this
//rooms.js
client.on('room_join', function(roomId){( //Catching the event
client.join(roomId); //Still able to handle the client property made in the sever.js
});
Is such thing possible, or can I only require the rooms.js file and use it as follow
var rooms = require('modules/rooms.js');
client.on('room_join', function(roomId){
rooms.join(roomId);
});
A prefered solution would be something with the following structure
//server.js
var fs = require( 'fs' );
var app = require('express')();
var https = require('https');
var messagesEvents = require('events/messages.js');
var roomEvents = require('events/rooms.js');
server.listen(1234);
// events/messages.js
var messages = require('../modules/messages.js');
io.on('connection', function(client){
client.on('message', function(data){
messages.send(client, data, io);
});
});
// modules/messages.js
function send(client, data, io){
return io.to(data.roomId).emit('message', {message: data.message});
}

How to make the websocket server be at a router?

I'm writing a websocket server using nodejs-ws module, but the server can only be at the root of the server, so how I can make it at a child router like localhost:3000/chat?
I need your help, thanks a lot!
Working example:
var ws = require('ws');
var http = require('http');
var httpServer = http.createServer();
httpServer.listen(3000, 'localhost');
var ws1 = new ws.Server({server:httpServer, path:"/chat"});
ws1.on('connection', function(){
console.log("connection on /chat");
});
var ws2 = new ws.Server({server:httpServer, path:"/notifications"});
ws2.on('connection', function(){
console.log("connection on /notifications");
});
could you please tell me how to use this in express?
To route websockets with Express I'd rather use express-ws-routes
var express = require('express');
var app = require('express-ws-routes')();
app.websocket('/myurl', function(info, cb, next) {
console.log(
'ws req from %s using origin %s',
info.req.originalUrl || info.req.url,
info.origin
);
cb(function(socket) {
socket.send('connected!');
});
});

Node-HTTP-Proxy error

I am trying to implement a node http proxy for the first time with my simple twitter tweeter. I have never used this before and tried following the docs (https://github.com/nodejitsu/node-http-proxy) with no luck. Can anyone point me in the right direction? Also, is it okay to run this locally on a mac? Thanks
var express = require('express');
var app = express();
var port = 8300;
var twitter = require('twitter');
var twit = new twitter({ keys and stuff })
var http = require('http'),
httpProxy = require('http-proxy');
twit.post('statuses/update', {status: "Hello world!"}
//this works
httpProxy.createProxyServer({target:'http://localhost:3000'}).listen(3000);
// Create your target server--- WHat exactly does this mean??
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(3000);
You should not use this lib for proxing you request. This lib is for make your own proxy server. Look at example how to use proxy with twitter lib

"not found" plaintext in browser, when trying to render template with swig on koajs

I am using koajs on node.js and the swig templating engine to learn and code a web service. At the moment the Browser only loads up the words 'not found'. The code worked before i tried to split the program up into multiple files. After then i tried to get it work, even with getting everything back together in one file, without success.
The html file at './templates/base.html' does exist.
For clarification, when I run 'node --harmony index.js' there are no errors and I do get the output 'listening on port 3000'. But when I try to load up the page in my browser, i get the plain text 'not found'.
Here are my files:
index.js:
var routes = require('./routes');
var server = require('./server');
routes.baseroute
server.init(3000);
server.js:
var serve = require('koa-static');
var koa = require('koa');
var app = koa();
var init = function(port){
app.use(serve('./public'));
app.listen(port);
console.log('\n ---> listening on port '+port);
};
exports.init = init;
routes.js:
var koa = require('koa');
var route = require('koa-route');
var views = require('./views');
var app = koa();
var baseroute = app.use(route.get('/', views.baseview));
exports.baseroute = baseroute;
views.js:
var swig = require('swig');
var data = require('./data');
var baseview = function*(){
var tpl = swig.compileFile('./templates/base.html');
this.body = tpl(data.basedata);
};
exports.baseview = baseview;
data.js:
var basedata = {user: 'testuser123'};
exports.basedata = basedata;
So what's really happening is after you split them into their own files you created a separate instance of koa in their own file.
See:-
var app = koa();
in both server.js and routes.js and koa thinks of them as separate apps. It's possible in koa to have more than one apps but you'd have to mount them for them to have any kind of linkage.
First, find the main file that you want your linkage to happen. I'm guessing it's server.js and expose other app from their file(route.js). Now when you're linking them just use mount('/', require('./routes')); and koa will link them as one unit. In short:-
//routes.js
var koa = require('koa');
...
...
var app = koa();
app.use(route.get('/', views.baseview));
module.exports = app;
//server.js
var app = require('koa');
var mount = require('koa-mount');
var routes = require('./routes');
...
...
var init = function(port){
app.use(serve('./public'));
app.use(mount('/route', routes));
app.listen(port);
console.log('\n ---> listening on port '+port);
};
exports.init = init;

socket.io parse connect (>= 2.4.1) signed session cookie

With the latest version of connect (as of 2012-07-26), I've found the following way to get a session ID from socket.io that will work with a connect-redis store.
var express = require('express')
, routes = require('./routes')
, fs = require('fs')
, http = require('http')
, io = require('socket.io')
, redis = require('connect-redis')
, connect = require('express/node_modules/connect')
, parseSignedCookie = connect.utils.parseSignedCookie
, cookie = require('express/node_modules/cookie');
var secret = '...';
var rStore = new(require('connect-redis')(express));
//...
var server = http.createServer(app);
var sio = io.listen(server);
sio.set('authorization', function(data, accept) {
if(data.headers.cookie) {
data.cookie = cookie.parse(data.headers.cookie);
data.sessionID = parseSignedCookie(data.cookie['connect.sid'], secret);
} else {
return accept('No cookie transmitted', false);
}
accept(null, true);
});
data.sessionID can then be used later such as
sio.sockets.on('connection', function(socket) {
console.log('New socket connection with ID: ' + socket.handshake.sessionID);
rStore.get(socket.handshake.sessionID, function(err, session) {
//...
});
});
Having to import so many from express (connect, a utility of connect, and the cookie module) seems like an overly roundabout way of getting the functions needed to parse connect's signed cookies. Has anyone found another way?
I was running into the same and just wrote a tiny module to abstract it. Here's how its usage looks like. It was written and tested using express 3 so should work fine with connect 2.4.x. Please let me know otherwise.
var SessionSockets = require('session.socket.io')
, sessionSockets = new SessionSockets(io, sessionStore, cookieParser);
sessionSockets.on('connection', function (err, socket, session) {
//your regular socket.io code goes here
});
For more details on how it works see https://github.com/wcamarao/session.socket.io

Categories

Resources