show url into console with node.js - node.js

how can i display the request.url into the console.log to see, which url someone called?
So i want to see into console for each call a line with the url.
Sorry, i'm a very beginner with node.js ;-)
Thanks for help.
//Lets require/import the HTTP module
var http = require('http');
//Lets define a port we want to listen to
const PORT=8083;
//We need a function which handles requests and send response
function handleRequest(request, response){
response.end('It Works!! Path Hit: ' + request.url);
}
//Create a server
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
console.log("URL:%s");
});

If you are using express you can setup a custom middleware, that gets called for every request.
// logging middleware
var num = 0;
app.use(function (req, res, next) {
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
var method = req.method;
var url = req.url;
console.log((++num) + ". IP " + ip + " " + method + " " + url);
next();
});
But you can do the same with your http module server :)

Related

Creating web server with express (node.js)

js and am trying to create a web server and server side code for my web application.
I understand express is used to get access to all static files.
I am trying to start a simple server using express as follows:
var express = require("express");
var url = require("url");
var http = require("http");
var port = 3000;
var app = express();
app.use(express.static(__dirname + "/Client"));
http.createServer(app).listen(port, function(req,res){
console.log("Server running at: " + "http://" + port);
res.writeHead(200,{
"Content-Type":"text/plain"
});
});
I cant seem to do anything with my res variable in my callback, which I am trying to use as a response object. Allowing me to do things like:
res.end(¨hello world¨);
Is this callback even allowed, or how can I start sending responses etc. I am on virtual box (linux) machine, and using res always gives error (undefined methods etc.). Thanks in advance,
http.createServer(app).listen(port, [hostname], [backlog], [callback])
There are no parameters given to the callback function. This is why req and res are undefined.
So you may change your code to:
app.listen(port, function(){
console.log("Server running at: " + "http://localhost:" + port);
});
app.get('/', function(req,res) {
res.status(200).send('Hello World!')
})
So take a look at the documentation of app.listen() and app.get()

Why express.vhost isn't working?

I create 3 node js servers.I'm trying to load server2 and server3 into server1.I'm trying with express.vhost but i can't succed.Here is my code:
server:
var application_root = __dirname,
express = require( 'express' ),
vhost = require( 'vhost' );
function createVirtualHost(domainName, dirPath) {
return vhost(domainName, express.static( dirPath ));
}
//Create server
var app = express();
//Create the virtual hosts
var host1 = createVirtualHost("http://localhost:8001", "/");
var host2 = createVirtualHost("http://localhost:8002", "/");
//Use the virtual hosts
app.use(host1);
//app.use(host2);
//Start server
var port = 80;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});
server 1 :
var http = require('http');
//Lets define a port we want to listen to
const PORT=8001;
//We need a function which handles requests and send response
function handleRequest(request, response){
response.end('It Works!! Path Hit: ' + request.url);
}
//Create a server
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});
module.exports=server;
server 3:
var http = require('http');
//Lets define a port we want to listen to
const PORT=8002;
//We need a function which handles requests and send response
function handleRequest(request, response){
response.end('It Works!! Path Hit: ' + request.url);
}
//Create a server
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});
I have these files in the same folder.Thanks for any help!

Intercept HTTP responses on an HTTPS server in Node.JS and Express

I'm just starting with node.js and express and I'm doing a simple HTTPS server. I've been working with nginx for some time and when I make an HTTP request to an HTTPS endpoint I get a "400 Bad Request" error. However, when using node.js the request never finishes.
How can I intercept an HTTP request in Express to be able to generate the "400 Bad Request" response?
This is my code:
var express = require('express');
var https = require('https');
var fs = require('fs');
var port = process.env.PORT || 8080;
var tls_options = {
key: fs.readFileSync('certs/server.key'),
cert: fs.readFileSync('certs/server.crt'),
ca: fs.readFileSync('certs/ca.crt'),
requestCert: true,
};
var app = express();
var router = express.Router();
router.get('/', function(req, res) {
res.json({ message: 'Checkpoint!!' });
});
app.use('/', router);
var secureServer = https.createServer(tls_options, app);
secureServer.listen(port);
console.log('Listening on port ' + port);
Until now the only thing I've been able to use is getting a 'connection' event every time a request arrives to the server:
secureServer.on('connection', function (stream) {
console.log('someone connected!');
});
Done. In fact, an HTTP request to an HTTPS socket ends after the default 120secs TLS handsahke timeout. This way I can end the request without waiting. I include the solution I used just for future references if anything needs the same functionality.
var secureServer = https.createServer(options, app);
secureServer.on('connection', function(socket) {
socket.on('data', function(data) {
var first_line = data.toString().split('\r\n')[0];
var pattern = /\bhttp\/1\.[01]$\b/i;
if (pattern.test(first_line)) {
var headers = {};
headers['Date'] = new Date().toUTCString();
headers['Connection'] = 'close';
var headers_string = '';
for (var name in headers) {
headers_string = headers_string + '\r\n' + name + ': ' + headers[name];
}
socket.end('HTTP/1.1 400 Bad Request' + headers_string);
}
});
There isn't a way of starting both HTTP and HTTPS servers on the same port. What most people do is either:
Start two servers (one HTTP and one HTTPS) on different ports, and redirect the HTTP traffic to HTTPS. Using Express it would mean the additional code:
// create two ports, one for HTTP and one for HTTPS
var port = process.env.PORT || 8080;
var httpsPort = 8081;
// redirect all HTTP requests to HTTPS
app.use(function(req, res, next) {
var hostname;
if (!req.secure) {
hostname = req.get("host").split(":")[0];
return res.redirect(["https://", hostname, ":", httpsPort, req.url].join(""));
}
next();
});
app.listen(port); // listen on HTTP
https.createServer(tls_options, app).listen(httpsPort); // listen on HTTPS
Or they use nginx or apache to handle outside connections (both HTTP and HTTPS) and redirect traffic to the Node server (which can then just run on HTTP).

How to get the port number in node.js when a request is processed?

If I have two node.js servers running, how can I tell which server called the processRequest function?
var http = require('http');
var https = require('https');
function processRequest(req, res) {
res.writeHead(200);
res.end("hello world, I'm on port: " + ???.port + "\n");
}
var server1 = http.createServer(processRequest).listen(80);
var server2 = https.createServer(processRequest).listen(443);
Originally I wanted the port number, but couldn't find the object/variable to give it to me. Based on the below answer it makes more sense to determine encrypted vs non-encrypted since the point is to know which of the http servers the request came in on.
The req parameter is an instance of IncomingMessage from which you can access the socket.
From there you can access both the localPort and remotePort.
Something like:
console.log(req.socket.localPort);
console.log(req.socket.remotePort);
This way you get the port number:
var http = require('http');
var server = http.createServer().listen(8080);
server.on('request', function(req, res){
res.writeHead(200, {"Content-Type": "text/html; charset: UTF-8"});
res.write("Hello from Node! ");
res.write(" Server listening on port " + this.address().port);
res.end();
});
In case you are using http://localhost:<port_number>, then you can get the port number using req.headers.host property.
Example:
const http = require('http');
const server = http.createServer((req, res)=>{
console.log(req.headers.host); // localhost:8080
console.log(req.headers.host.split(':')[1]); // 8080
})
server.listen(8080);
Instead of checking port numbers, you can also check the server instance or the connection object:
var http = require('http'),
https = require('https');
function processRequest(req, res) {
var isSSL = (req.socket.encrypted ? true : false);
// alternate method:
// var isSSL = (this instanceof https.Server);
// or if you want to check against a specific server instance:
// var isServer1 = (this === server1);
res.writeHead(200);
res.end('hello world, i am' + (!isSSL ? ' not' : '') + ' encrypted!\n');
}
var server1 = http.createServer(processRequest).listen(80);
var server2 = https.createServer(processRequest).listen(443);

Access control origin in connect (node.js)

I am running static pages via connect
var connect = require('connect');
connect.createServer(
connect.static(__dirname)).listen(8080);
I have to add a response header to the above code to bypass the access control
response.writeHead(200, {
'Content-Type': 'text/html',
'Access-Control-Allow-Origin' : '*'});
How do I add it to the above connect code.
I answered this question here
Relevant code
var http = require("http");
var connect = require('connect');
var app = connect()
.use(connect.logger('dev'))
.use(connect.static('home'))
.use(function(req, res){
res.setHeader("Access-Control-Allow-Origin", "http://example.com");
res.end('hello world\n');
});
var server = http.createServer(app);
server.listen(9999, function () {
console.log('server is listening');
});
Enable cors provides excellent resource for adding cors to your server.
If you got to send the cors headers with every static file that you serve and you have to use connect then do this
navigate to connect\node_modules\send\lib\send.js
look for the setHeader function in the file. This is the function that actually sets header to your static resources. Just add
res.setHeader("Access-Control-Allow-Origin", "your domain");
and all of your files will have the cors header in them
If you are just using connect to serve static files and don't require any of the other functionality consider using send instead. This way you will have access to all of it's methods directly and won't need to edit files. You can simply add headers from your create server method. Here is the sample code
var http = require("http");
var connect = require('connect');
var send = require('send');
var url = require('url');
var app = http.createServer(function(req, res){
// your custom error-handling logic:
function error(err) {
res.statusCode = err.status || 500;
res.end(err.message);
}
// your custom directory handling logic:
function redirect() {
res.statusCode = 301;
res.setHeader('Location', req.url + '/');
res.end('Redirecting to ' + req.url + '/');
}
function setRoot(){
res.setHeader("Access-Control-Allow-Origin",
"http://example.com");
return './public';
}
function setIndex(){
res.setHeader("Access-Control-Allow-Origin",
"http://example.com");
return '/index.html';
}
send(req, url.parse(req.url).pathname)
.root(setRoot()).index(setIndex())
.on('error', error)
.on('directory', redirect)
.pipe(res);
}).listen(3000);

Resources