Include CSS and JS in HTTP server? - node.js

I saw that you can use connect to use serve static files in a Node.js HTTP server like this:
var http = require('http');
var connect = require('connect');
var app = connect().use(connect.static(__dirname + path));
http.createServer(app).listen(8080);
How would I implement this in my current handler?
var http = require("http");
var handler = function(request, response){
// code
}
http.createServer(handler);
Is this even possible? If so, how can I accomplish it?

Unless you want to use an older version of connect that might not function properly, you'd have to install serve-static to do what you're trying to do. See this answer https://stackoverflow.com/a/24347442/5382465
var finalhandler = require('finalhandler')
var http = require('http')
var serveStatic = require('serve-static')
// Serve up public folder
var serve = serveStatic('public', {'index': ['index.html', 'index.htm']})
// Create server
var handler = http.createServer(function onRequest (req, res) {
serve(req, res, finalhandler(req, res))
})
// Listen
handler.listen(3000)

Related

Why we pass "app" in http.createServer(app)

Why we pass "app" in http.createServer(app) as we can also pass
e.g :
var app = require('./app')
const http = require('http')
const port = 3500 || process.env.PORT
var server = http.createServer(app) //here we pass app
in other code we pass some different argument such as this
https.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(port)
In your first example, I'm assuming that app represents an Express instance from something like this:
const app = express();
If so, then app is a request handler function that also has properties. You can pass it like this:
var server = http.createServer(app);
because that app function is specifically designed to be an http request listener which is passed the arguments (req, res) from an incoming http request as you can see here in the doc.
Or, in Express, you can also do:
const server = app.listen(80);
In that case, it will do the http.createServer(app) for you and then also call server.listen(port) and return the new server instance.
When you do this:
https.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(port);
you are just making your own function that's built to handle an incoming http request instead of using the one that the Express library makes for you.
Quoting the Express documentation:
The app returned by express() is in fact a JavaScript Function, designed to be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):
var express = require('express')
var https = require('https')
var http = require('http')
var app = express()
http.createServer(app).listen(80)
https.createServer(options, app).listen(443)
https://expressjs.com/en/api.html

Websocket With Socket.io & Angular

I want to create a websocket to add a communication between my angular app and my database. The app shall be able to save a question in a database & to notify the user when somebody answered.
Unfortunately I tried some tutorials which all don't work. I'm totally new to this because I use apache usually. So If you know a "working", very basic (beginner) tutorial, which doesn't require to install lots of additional things like yeoman etc. I would be glad.
In the current tutorial I get the error message:
You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.
My server.js:
var connect = require('connect'),
serveStatic = require('serve-static'),
socket = require('socket.io');
var server = connect();
server.use(serveStatic(__dirname+'/../client'));
server.listen(8080);
var io = socket.listen(server);
console.log("Server started and listen to http://127.0.0.1:8080");
without
var io = socket.listen(server);
it serves my static page.
This error is on my other approach:
has no method 'use'
My server.js
var connect = require('connect');
var http = require('http');
var serveStatic = require('serve-static');
var app = connect();
var server = http.createServer(app).use(serveStatic(__dirname+'/../client')).listen(3000);
var socket = require('socket.io');
var io = socket.listen(server);
As always if you struggle long the solution comes quick after posting. That one works for the beginning:
var connect = require('connect');
var http = require('http');
var app = connect();
var fs = require('fs');
var index = fs.readFileSync(__dirname+'/../client/index.html');
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end(index);
}).listen(3000);
var socket = require('socket.io');
var io = socket.listen(server);

how to use Express 4 with Socket.io 0.9.x?

I am a ios developer, the Objc-Socket.io library is still support socket.io 0.9.x
I use Express 4.0 with my nodejs server:
server.js
var express = require('express')();
var io = require('socket.io');
io.listen(express);
But I run it in terminal, it throw me an error:
% node test
Socket.IO's `listen()` method expects an `http.Server` instance
as its first parameter. Are you migrating from Express 2.x to 3.x?
If so, check out the "Socket.IO compatibility" section at:
https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x
This code should do the trick:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app).listen(1337);
var io = require('socket.io').listen(server);
io.on('connection', function(socket) {
//emit and listen messages
});
app.get('/', function(req, res) {
//do something
});

Node.js: url route with the CNAME record

I want to map example.org and cname.example.org to two different node.js app.
But use no http web server such as nginx.
And the web framework is express.
So is there are any middleware in express or node.js to do this?
Express uses connect so you can do this:
var express = require('express'),
app = express();
app.use(express.vhost('example.org', require('./exampleApp/')));
app.use(express.vhost('cname.example.org', require('./cnameExampleApp/')));
app.listen(80);
There is also an example on github:
https://github.com/visionmedia/express/tree/master/examples/vhost
And here the reference for connect.vhost:
http://www.senchalabs.org/connect/vhost.html
Edit: In recent express versions, most middlewares like vhost are not included, so you will have to install them manually.
First, run:
$ npm install --save vhost
Updated code snippet:
const express = require("express");
const vhost = require("vhost");
const app = express();
app.use(vhost("example.org", require("./exampleApp/")));
app.use(vhost("cname.example.org", require("./cnameExampleApp/")));
app.listen(80);
You need a proxy like nginx in anyway if your 2 node apps are hosted on the same host.
var request = require('request');
var proxy = require('http').createServer(function (req, res) {
// distribute by request header 'host'
var targetHost = req.headers.host;
if (targetHost === 'example.org') {
req.pipe(request('http://your-node-app1' + req.url)).pipe(res);
} else if (targetHost === 'cname.example.org') {
req.pipe(request('http://your-node-app2' + req.url)).pipe(res);
} else { // not found or host is invalid
res.statusCode = 404;
res.end('host is not found!');
}
});
proxy.listen(80); // assume it listens to port 80

connect.static() interpret PHP files with node.js and connect

I successfully configured node with connect and nowjs. Calling localhost:8001/test.html and localhost:8001/chat.html works without any problems. But when calling a PHP-file localhost:8001/test.php my browser wants me to download that file. Obviously connect.static won't interpret the PHP file. Is there any other possibility to get it work for html and php files?
Thanks
var http = require('http');
var connect = require('connect');
var nowjs = require("now");
var app = connect();
app.use(connect.static('/var/www/www.domain.com/htdocs'));
app.use(function(req, res){
res.end();
});
var server = http.createServer(app).listen(8001);
var everyone = nowjs.initialize(server);

Resources