To parse the query string not working - node.js

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

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);

Sending a single-packet HTTP response in Node.js

To show my students a simple HTTP request and response that they could capture using Wireshark, I whipped up a simple Node.js HTTP server:
var fs = require('fs');
var http = require('http');
var port = 80;
var file = process.argv[2]; //This file contains a 42 byte HTML page
http.createServer(function (req, res) {
res.writeHead(200, { 'content-type' : 'text/html' }); // Sends first packet
fs.createReadStream(file).pipe(res); // Sends second packet
}).listen(port);
Unfortunately, the two lines transmitting the HTTP header and the HTML are sent as two separate TCP packets (even though they are both quite small). It would be simpler for my students if the HTTP header and HTML were just one packet. How could I change my code to do this?
var http = require('http');
var fs = require('fs');
var file = process.argv[2];
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html;"});
fs.readFile(file, function (err, html) {
if (err) {
throw err;
}
response.write(html);
response.end();
});
}).listen(8000);
the reason it won't work is that Node.js runs everything asynchronously. When you are loading your html file, the server creation starts the same time. By the time you are about to write your html to your tcp socket, the file most likely won't be ready.
I see what you were trying to do before... I misread your code because of the indentation. Let me know if this snippet works.
try using something like-
var file = process.argv[2];
fs.readFile(file, function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8000);
});

NodeJS run server for receiving POST and serve GET

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;

Node.js double console.log output

I'm learning Node.js and I'd like to understand the "why" when code spits out duplicated console.log outputs but only a single response.write outputs.
Heres my simple code example:
var http = require('http');
http.createServer(function(request, response){
response.writeHead(200, {'Content-type': 'text/plain'});
console.log('hello 1');
response.write('Hello world');
console.log('hello 2');
response.end();
}).listen(8000);
And on my console/terminal I get:
hello 1
hello 2
hello 1
hello 2
Thanks.
Some browsers also send a request to locate the favicon.ico file. Since the file isn't present by default, a browser(Chrome in particular) will always send two requests: one for the originally requested file and another for favicon.ico. This is a known bug in Chrome and has been fixed in version 29. Firefox, however, requests for favicon.ico only for the first request. If you console.log the request URI path, you must see a request to localhost:8000/favicon.ico.
var http = require('http');
http.createServer(function(request, response){
response.writeHead(200, {'Content-type': 'text/plain'});
if(request.url === '/favicon.ico') {
console.log('Favicon was requested');
}
console.log('hello 1');
response.write('Hello world');
console.log('hello 2');
response.end();
}).listen(8000);
I've had the same problem myself, and I found out that using something like
var http = require('http');
http.createServer(function(req,res) {
if(req.url === '/favicon.ico')
{
//everything here is ignored
}
res.writeHead(200,{"Content-Type": "text/plain"});
res.write("Hello World\n");
res.end();
console.log("Connection made");
}).listen(1337, "127.0.0.1");
console.log("Server running at http://127.0.0.1:1337/");
is enough to avoid that behaviour. For some reason, when I check req.url and compare it to '/favicon.ico' nothing is sent to console, in fact, everything in that block is ignored. I don't know if this behaviour is expected, but you sure could try it.
If you output the header you're telling the server that you found favicon, hence the response is processed and no matter what you get that double console.log(). Instead, end it before sending a writeHead() or send a 404.
var http = require('http');
http.createServer(function (req, res) {
if(req.url === '/favicon.ico') {
res.writeHead(404);
res.end();
} else {
res.writeHead(200, {'Content-Type': 'text/plain'});
}
//code here...
res.end();
}
i think that this problem still persists in chrome Version 67.0.3396.87 (32-bit) because when i ran my nodeJS script i saw 2 console.log() statements one was able to print out the query the other was not, so i corrected my code so as to see console.log() statements only once, it was simple all i had to do was add a return statement if the request.url was == (equal to)"/favicon.ico" in the beginning of the code and everything worked fine
previous code
var http = require('http');
var url = require('url');
http.createServer((request,response)=>{
var q = url.parse(request.url,true).query;
console.log(request.url);
console.log('hey there! we got a request from '+q.name+' !');
}).listen(8080);
and the output was :
/?name=harshit
hey there we got a request from harshit !
/favicon.ico
hey there we got a request from undefined !
code after debugging :
var http = require('http');
var url = require('url');
http.createServer((request,response)=>{
if(request.url == "/favicon.ico"){
return ;
}
var q = url.parse(request.url,true).query;
console.log(request.url);
console.log('hey there! we got a request from '+q.name+' !');
}).listen(8080);
output :
/?name=harshit
hey there we got a request from : harshit !
in a nutshell the duplication as it is mentioned before is a result of the favicon request so to avoid this problem, I propose you this simple snipet:
var pathname = url.parse(request.url).pathname;
if(pathname != '/favicon.ico')
console.log('hello 1');
It can also be a Chrome plugin like JSONView. I was just trying to figure it out until I tried incognito and realized it was no longer causing the problem. Also was requesting a JSON file.

Error 330 when Gzipping a response from nodejs server

I want to gzip a file hold it in memory and whenever a request comes from the client, i want to output the gzipped data. However I get a error 330 message on my browser (i am using the latest version of chrome)
The code below looks straight forward to me, is there something else I am missing?
var http = require('http');
var url = require('url');
var fs = require('fs');
var zlib = require('zlib');
var gzippedData = '';
//read file into memory
fs.readFile('layout.html', function(err, data){
if(err) throw err;
zlib.gzip(data, function(err, buffer) {
if (err) throw err;
gzippedData = buffer.toString('binary');
});
});
var server = http.createServer(function(req, res){
var path = url.parse(req.url).pathname;
switch (path){
case '/':
res.writeHead(200, {'content-encoding': 'gzip'});
res.write(gzippedData);
res.end();
break;
default:
res.writeHead(404);
res.write('404');
res.end();
}});
server.listen(8080);
Change
gzippedData = buffer.toString('binary');
to
gzippedData = buffer;
And you should be good to go!
EDIT: This is because res.write will encode the response as utf8 by default. You could instead change that to res.write(gzippedData, 'binary'), but that's unnecessary. It's cheaper to just keep the reference to the buffer instead of allocating a js string and encoding that yet again.

Resources