NodeJS run server for receiving POST and serve GET - node.js

1) Running a NodeJS server on localmachine
2) One device with App making a POST req to Node server.
3) XAMPP page making a GET request to get what device (from point 2) sent to Node server.
hope that's clear.
this is what I have, but GET receives undefined.
POST logs key1=value1
var http = require('http');
http.createServer(function (req, res) {
console.log(req.method);
var txt;
if(req.method == "POST") {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
var url = require("url"),
parsedUrl = url.parse(req.url, false), // true to get query as object
queryAsObject = parsedUrl.query;
txt = JSON.stringify(queryAsObject);
console.log(txt);
} else {
// for GET requests, serve up the contents in 'index.html'
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello Worldzz\n'); // I WANT TO PASS txt here.
console.log("jaa" + txt);
}
}).listen(1337, 'my.ip.here');
console.log('Server running at http://my.ip.here:1337/');
-- update. CHECKing
function checkServer() {
$.ajax({
type: "GET",
url: "http://my.ip.here:1337/",
async: false,
}).success(function( text ) {
console.log("res" + text);
$( "h2" ).text( text );
});
}

This is just a simple scope problem. Since you want all requests to share the same txt var, you'll need to define txt in a place where all requests can access it.
var http = require('http');
var txt;
http.createServer(function (req, res) {
console.log(req.method);
//var txt;

Related

Node js undefined printed using fs.appendFile

I have just started out learning Node js. I can't understand why in output.txt I am seeing "2020 Septemberundefined undefined" in output.txt when I call:
http://localhost/?month=September&year=2020
I am expecting to see just "2020 September" in output.txt.
var http = require('http');
var url = require('url');
var fs = require('fs');
//create a server object:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var q = url.parse(req.url, true).query;
var txt = q.year + " " + q.month;
fs.appendFile('output.txt', txt, function (err) {
// nothing
});
res.end(); //end the respons
}).listen(8080); //the server object listens on port 8080
The favorite icon. Add console.log(req.url). You will see that the browser makes two requests.
Browser is sending requests for http://localhost:8080/favicon.ico, behind the scenes.
So whenever you hit http://localhost:8080/?month=September&year=2020,
node write "2020 September" to output.txt file, meanwhile browser hit favicon.ico request then node write again "undefined undefined" in output.txt file.
if you want to skip favicon.ico request,
var http = require('http');
var url = require('url');
var fs = require('fs');
//create a server object:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
if (req.url != '/favicon.ico') {
var q = url.parse(req.url, true).query;
var txt = q.year + " " + q.month;
fs.appendFile('output.txt', txt, function (err) {
// nothing
});
}
res.end(); //end the respons
}).listen(8080);

NodeJS Agent similar to Java agent

I am trying to create node agent similar to java agent to gather the performance of running nodejs application
I found appmetrics npm package and it works fine , if I include that to the exisitng nodejs script but I am trying to run as an agent without modifying existing nodejs script
Sample which explains my issue which works fine
var http = require("http");
var appmetrics = require('appmetrics');
var monitoring = appmetrics.monitor();
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8083);
// Console will print the message
console.log('Server running at http://127.0.0.1:8083/');
monitoring.on('initialized', function (env) {
env = monitoring.getEnvironment();
for (var entry in env) {
console.log(entry + ':' + env[entry]);
};
});
monitoring.on('cpu', function (cpu) {
console.log('[' + new Date(cpu.time) + '] CPU: ' + cpu.process);
});
Issue is to have appmetric separately and nodejs hello world script separately and running them together
helloworld.js
var http = require("http");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8083);
// Console will print the message
console.log('Server running at http://127.0.0.1:8083/');
monitor.js
var appmetrics = require('appmetrics');
var monitoring = appmetrics.monitor();
monitoring.on('initialized', function (env) {
env = monitoring.getEnvironment();
for (var entry in env) {
console.log(entry + ':' + env[entry]);
};
});
monitoring.on('cpu', function (cpu) {
console.log('[' + new Date(cpu.time) + '] CPU: ' + cpu.process);
});
Trying to run above mentioned two scripts at a time using
node which is not working
node helloworld.js && node monitor.js

To parse the query string not working

Im self-educating Node.js. I have created two simple HTML files (summer.html and winter.html) and noded the JS on node.js. I went on localhost:5354/summer.html (and winter.html). Nothing is showing up and I got an error message
This site can’t be reached
The connection was reset.
Try:
Checking the connection
Checking the proxy and the firewall
Running Windows Network Diagnostics
ERR_CONNECTION_RESET
I have tested other lessons and was able to display results on localhost:5354/ but this one doesnt work. What did I do wrong?
JS
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(5343);
Hit this URL
localhost:5343/summer.html
Because, You listen in 5343 PORT. But you hit 5354 Port

node js incoming request sourceIP

For example:
http.createServer(function (request, response) {
request.on("end", function () {
});
});
Using Request, how I can I find the source IP of the request?
Depending on whether the request is made by a proxy forward or direct connection the source ip address may be stored at different places. You have to check req.header['x-forwarded-for'] first and then req.connection.remoteAddress. An example function is shown in this gist.
Here is a working example:
var http = require('http');
var getClientIp = function(req) {
var ipAddress = null;
var forwardedIpsStr = req.headers['x-forwarded-for'];
if (forwardedIpsStr) {
ipAddress = forwardedIpsStr[0];
}
if (!ipAddress) {
ipAddress = req.connection.remoteAddress;
}
return ipAddress;
};
var server = http.createServer();
server.on('request', function(req, res) {
console.log(getClientIp(req));
res.writeHead(200, {'Content-Type': 'text/plain'});
return res.end('Hello World\n');
});
server.listen(9000, 'localhost');
the getClientIp function was taken from here with some minor changes. Note that the contents of x-forwarded-for is an array containing proxy IPs, (read more here), so you may wish to inspect more than the first element.

Unable to set headers in node.js in POST method

I have a case where i have to read the data from the request body and create a file and write the data into it. If the operation is successful I set the response header to 201 and add the location of file in Location header. The file creation is done using Java methods and node.js code is below.
var server = http.createServer(function(req, res)
{
var body = "";
req.on("data", function(chunk)
{
body += chunk.toString();
});
req.on("end", function() {
var rtn = obj.AddonPostMethod(filepath,body);
if(rtn.length < 13)
{
res.writeHead(201, {"Location" : rtn});
res.end();
}
else
{
res.writeHead(400, {"Content-Type" : application/json"});
res.write(''+rtn);
res.end();
}
});
}});
The problem is that the response headers are not getting updated and are always set to the default headers 200 Ok. In addition to this the server is always busy even after the response is received.
I don't think you're actually listening on a port with the code you reference.
var http = require('http');
http.createServer(function(req,res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
You never declare the http object as actually listening on a port/ip with the .listen() function.
Also, you don't need to wait for the req object to emit anything to respond. The function is called when the request is complete. You can listen for specific requests and route them appopriately by storing the http.Server object to a variable.
var server = http.createServer();
server.listen(8000);
server.on('request', function(req,res){ /* do something with the request */ });
More documentation on the http object can be found on the node.js documents for http

Resources