httpdispatcher returning no or blank response - node.js

I have the following simple code for a nodejs server....
var http = require('http');
var port = 1337;
var dispatcher = require('httpdispatcher');
dispatcher.setStaticDirname(__dirname);
dispatcher.setStatic('');
dispatcher.onGet("/page1", function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Page One');
});
var server = http.createServer().listen(port);
server.on('request', function (req, res) {
console.log('GOT');
dispatcher.dispatch(req, res);
});
console.log('Listening on port %s', port);
when I goto http://localhost:1337/index.html it is showing up correctly but when I do http://localhost:1337/page1 nothing happens...how can I get it to function properly...

You need to define your custom dispatcher events, in this case "/page1", before setting the static dispatcher. Otherwise static hogs every possible path remaining to check against the file system.
dispatcher.onGet("/page1", function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Page One');
});
dispatcher.setStaticDirname(__dirname);
dispatcher.setStatic('');
Your revised code will look like this:
var http = require('http');
var port = 1337;
var dispatcher = require('httpdispatcher');
dispatcher.onGet("/page1", function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Page One');
});
dispatcher.setStaticDirname(__dirname);
dispatcher.setStatic('');
var server = http.createServer().listen(port);
server.on('request', function (req, res) {
console.log('GOT');
dispatcher.dispatch(req, res);
});
console.log('Listening on port %s', port);
Tested and works

Related

node.js websocket data transfer calculation

i proxy websocket with following code, and i want know how i can calculate how much data transferred(upload/download), i used data event but received number is inconsequent
var http = require('http'),
httpProxy = require('http-proxy');
console.log('connected')
var proxy = new httpProxy.createProxyServer({
target: {
host: 'someIP',
port: 30534,
}
});
var proxyServer = http.createServer(function (req, res) {
proxy.web(req, res);
});
let byte= 0
proxyServer.on('upgrade', function (req, socket, head) {
proxy.ws(req, socket, head);
//here not working as well, the number is not real
req.socket.on('data', (message) => {
byte+= Buffer.byteLength(message)
console.log('megaByte ', megaByte / 1000 / 1000)
})
proxy.on('error', (err) => {
})
proxy.on('proxyRes', function (proxyRes, req, res) {
console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
});
});
proxyServer.listen(8015);

How serve client javascript modules in node.js

I'm new programmer to node.js. I trying to create vanilla server in node.js. In my client, I used ES6 modules. when I start my server and search for http://localhost:3000/ in my browser, HTML and CSS loaded but for javascript have this error:
I have four javascript modules for client side and in HTML I use this code for load javascript moduls:
<script type="module" src="js/controller.js" async></script>
My server code :
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 3000;
const server = http.createServer();
server.on('request', (req, res) => {
let routes = {
'GET': {
'/': indexHtml,
}
}
console.log(req.url)
let handler = routes[req.method][req.url];
handler = handler || readFile;
handler(req, res);
})
server.listen(PORT, () => {
console.log(`Listening on port ${PORT}...`)
});
function indexHtml(req, res) {
readFile({ url: '/index.html' }, res);
}
function readFile(req, res) {
var filePath = path.join(__dirname, '../client/', req.url);
// console.log(filePath)
fs.readFile(filePath, (error, data) => {
if (error) {
res.writeHead(404);
res.write('Not found error 404');
res.end()
} else {
res.writeHead(200);
res.write(data);
res.end();
}
})
}
How can I solve this error and serve javascript modules, Thanks a lot for your help.
With comment #derpirscher, I change my reader function with this code :
function readFile(req, res) {
var filePath = path.join(__dirname, '../client/', req.url);
fs.readFile(filePath, (error, data) => {
if (error) {
res.setHeader('Content-Type', 'text/html');
res.writeHead(404);
res.write('Not found error 404');
res.end()
} else {
const url = req.url === '/' ? '/index.html' : req.url;
if (req.url.includes('js')) res.setHeader('Content-Type', 'application/javascript');
if (req.url.includes('css')) res.setHeader('Content-Type', 'text/css');
if (req.url.includes('html')) res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.write(data);
res.end();
}
})
}

Node.js HTTP Server Routing

below node.js code is using express to route to different urls, how can I do the same with http instead of express?
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
res.send('Welcome Home');
});
app.get('/tcs', function (req, res) {
res.send('HI RCSer');
});
// Handle 404 - Keep this as a last route
app.use(function(req, res, next) {
res.status(404);
res.send('404: File Not Found');
});
app.listen(8080, function () {
console.log('Example app listening on port 8080!');
});
Here's a quick example. Obviously, there are many ways of doing this, and this is probably not the most scalable and efficient way, but it will hopefully give you an idea.
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
req.on('error', err => {
console.error(err);
// Handle error...
res.statusCode = 400;
res.end('400: Bad Request');
return;
});
res.on('error', err => {
console.error(err);
// Handle error...
});
fs.readFile('./public' + req.url, (err, data) => {
if (err) {
if (req.url === '/' && req.method === 'GET') {
res.end('Welcome Home');
} else if (req.url === '/tcs' && req.method === 'GET') {
res.end('HI RCSer');
} else {
res.statusCode = 404;
res.end('404: File Not Found');
}
} else {
// NOTE: The file name could be parsed to determine the
// appropriate data type to return. This is just a quick
// example.
res.setHeader('Content-Type', 'application/octet-stream');
res.end(data);
}
});
});
server.listen(8080, () => {
console.log('Example app listening on port 8080!');
});
Try the code below . It is a pretty basic example
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'}); // http header
var url = req.url;
if(url ==='/about'){
res.write('<h1>about us page<h1>'); //write a response
res.end(); //end the response
}else if(url ==='/contact'){
res.write('<h1>contact us page<h1>'); //write a response
res.end(); //end the response
}else{
res.write('<h1>Hello World!<h1>'); //write a response
res.end(); //end the response
}
}).listen(3000, function(){
console.log("server start at port 3000"); //the server object listens on port 3000
});
express can also be used by http directly.
From: https://expressjs.com/en/4x/api.html#app.listen
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.
var http = require('http')
var express = require('express')
var app = express()
http.createServer(app).listen(80)
With this, you can still make use of express for routing, while keeping native http support.

Node taking too long to respond

I wrote a very simple program to demonstrate request handling in Node (actually following a tutorial), but the server seems to take forever to respond to the GET / request. Here's the code I'm using:
const http = require('http');
const url = require('url');
let routes = {
'GET': {
'/': (req, res) => {
res.writeHead(200, {'Content-type': 'text/html'});
res.end('GET /');
}
},
'POST': {
},
'NA': (req, res) => {
res.writeHead(404);
res.end('Content not found');
}
}
function router(req, res) {
let baseURI = url.parse(req.url, true);
// the function that gets resolved and used to handle the request
let resolveRoute = routes[req.method][baseURI.pathname];
}
http
.createServer(router).listen(3001, () => {
console.log('Listening on port 3001');
});
Something I'm doing wrong?
Found it myself.
I was resolving the handler function but not calling it. Adding resolveRoute(req, res); to the end of the router() function makes it work. :)

nodejs node-http-proxy setup with cache

I'm trying to setup node-http-proxy module with caching
node-http-proxy module. I've managed to configure node-http-proxy to do what I need to do in terms of proxying calls, but I would like to find a way to cache some of these calls.
My current code is as follows (omitted some config bootstrapping):
var http = require('http');
var https = require('https');
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});
var fs = require('fs');
var handler = function(req, res) {
proxy.web(req, res, {target: 'http://localhost:9000'});
};
var server = http.createServer(handler).listen(config.children.http.port, function() {
console.log('Listening on port %d', server.address().port);
});
var secure = https.createServer(config.children.https.options, handler).listen(config.children.https.port, function() {
console.log('Listening on port %d', secure.address().port);
});
Inside the handler function, I would like to be able to somehow capture what the proxy is reading from "target" and stream it into a fs.createWriteStream('/somepath') before piping it out to res. Then I would modify my function to do look to something along the line:
var handler = function(req, res) {
var path = '/somepath';
fs.exists(path, function(exists) {
if(exists) {
console.log('is file');
fs.createReadStream(path).pipe(res);
} else {
console.log('proxying');
// Here I need to find a way to write into path
proxy.web(req, res, {target: 'http://localhost:9000'});
}
});
};
Does anyone know how to do this ?
The answer to the question ended up being very simple:
var handler = function(req, res, next) {
var path = '/tmp/file';
fs.exists(path, function(exists) {
if(exists) {
fs.createReadStream(path).pipe(res);
} else {
proxy.on('proxyRes', function(proxyRes, req, res) {
proxyRes.pipe(fs.createWriteStream(path));
});
proxy.web(req, res, {target: 'http://localhost:9000'});
}
});
};

Resources