Why we pass "app" in http.createServer(app) - node.js

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

Related

Express server does not receive request, http module server does

I am making a HTTP server for a Biometric device. I cannot make changes to the devices firmware. I can just add the server ip.
So I first made an express server to receive requests, but it didnt receive any. Later I made a server using http module of Nodejs and voila it was able to do so.
The problem is writing a server for a very big application in http module would be difficult and there is very less support available for it. I'd prefer to user Express. Any Ideas why express is failing?
Edit:
So someone asked for code here they are:
http module
var http = require('http');
var port = 7005;
var s = http.createServer();
s.on('request', function(request, response) {
response.writeHead(200);
console.log(request.method);
console.log(request.headers);
console.log(request.data);
response.write('hi');
response.end();
});
s.listen(port);
console.log('Browse to http://127.0.0.1:' + port);
Express Server:
var express = require('express')
var app = express()
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
// respond with "hello world" when a GET request is made to the homepage
app.all('/', function (req, res) {
res.send('hello world')
console.log(req.method + " Request Aayi");
console.log(req.body);
});
app.listen(7005);

Axios can GET but not POST to the same URL

I'm building a react app
In one component I'm writing this GET request which works:
In another component I'm writing this POST request:
Which then returns this 404 error:
And I have no idea how my GET works but my POST returns 404:not found when I'm requesting the same file both times?
UPDATE:
I'm running a node.js server now but it's a bit of a frankenstein's monster as this really isn't an area I have an understanding of. Does anyone know what I'm doing wrong?
// Server setup from node.js website
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// Trying to listen for data from React app to feed into JSON (broken)
var express = require("express");
var myParser = require("body-parser");
var app = express();
app.use(myParser.urlencoded({extended : true}));
app.post("/scene-setup.json", function(request, response) {
console.log(request.body); //This prints the JSON document received (if it is a JSON document)
});
app.listen(3001);
// Updating JSON file with "obj" (working)
var jsonfile = require('jsonfile')
var file = './scene-setup.json'
var obj = {name: 'JP'}
jsonfile.writeFile(file, obj, function (err) {
console.error(err)
})
Axios is used for making HTTP requests. So, you should have a backend server running that can handle these requests. I am not sure what exactly is the data that you want to save. If you need access to that data, should be saving it on the backend.
If you want to save some data just on the client side, HTML5 filesystem API might be something you want to look at. It can manage some data in the limited sandboxed part of user's filesystem.

Include CSS and JS in HTTP server?

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)

Why do many express.js (web framework) examples attach express object to http object?

What's the meaning of passing express object to http object in this example?
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
Many examples do this. I don't quite know what it means.
Some other examples don't use http at all. Here's example from Express.js website (http://expressjs.com/starter/hello-world.html), and it doesn't use http object:
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
Is there any difference at all? Does the second example still use http somehow? Or does it use express's own http server?
In the first example, the http module's Server method is being called, which is effectively an alias for createServer. You can see the relevant line here. The argument is essentially a function which accepts parameters request, response as expected of a requestListener.
In the second example, Express already requires http in its own module, so it is not necessary for the user to require it explicitly.
The main difference is that you are creating an instance of http.Server by yourself in the former, while Express creates a server instance for you in the latter. Instantiating a server by yourself is necessary if you wish to use the https module instead of http.

How to initialize nowjs on express with virtual hosts

I need to initialize nowjs on this express server with vhosts.. How do I do that?
var host_api = express()
.get('/', function(req, res){
});
var host_secure = express()
.get('/', function(req, res){
});
express()
.use(vhost('api.domain.com', host_api))
.use(vhost('secure.domain.com', host_secure))
.listen(3000);
Initialize nowjs on simple http
var http = require('http'),
nowjs = require('now');
httpServer = http.createServer(function (req, res) {
res.send('Hello World\n');
});
httpServer.listen(3000);
var everyone = nowjs.initialize(httpServer);
Connect (on which Express is built) includes the required code to run vhosts.
You can see the documentation here: http://www.senchalabs.org/connect/vhost.html
For example:
connect() // Or "app" if app is an express application (see example below)
.use(connect.vhost('foo.com', fooApp))
.use(connect.vhost('bar.com', barApp))
.use(connect.vhost('*.com', mainApp))
Each "app" (fooApp, barApp, mainApp) is either a Node.js HTTP server or a Connect/Express app. You can create each app into a separate js file, and then include it:
var fooApp = require('foo/app.js').app
An example can be seen here: http://www.jondev.net/articles/vHosts_with_Node.JS_and_Express

Resources