Why the node.js script is call twice? - javascript

I am a beginner in Node.js
I write the first script in Node.js like the below:
var count = 0;
var http = require('http');
var serv = http.createServer(function (req, res) {
count++;
console.log("why two?:" + count);
res.writeHead(200,{'Content-Type': 'text/html'});
require('colors');
if (count % 2 == 0) {
console.log('count:' + count);
console.log('smashing node'.rainbow);
res.end('<marquee>Smashing Node</marquee>');
} else {
console.log('count:' + count);
console.log('WTF'.rainbow);
res.end('<h4>Smashing Node</h4>');
}
});
serv.listen(3000);
Then I run this script
node first.js
In browser, access http://localhost:3000
And the result in console is:
why two?:1
count:1
WTF
why two?:2
count:2
smashing node
Why the code is called twice?
Thanks

Because two requests are being made.
Probably one is for / and the other is for /favicon.ico.
Your code doesn't care what the path is when it handles a request.
You can test that by looking in the Net tab of your browser's developer tools or examining the contents of the req object.

That anonymous function is called whenever you request on http://localhost:3000
So maybe somehow you're requesting twice (e.g. for / and /favicon.ico)
Try opening chrome dev tools, and in console tab you'll maybe see an error, that favicon.ico wasn't found.
or you can use morgan to keep track of requests:
var app = require('express')();
var morgan = require('morgan');
app.use(morgan('dev'));
It will log every request, with codes and URL-s. It needs express though.

var count = 0;
var http = require('http');
var serv = http.createServer();
serv.on('request',function(req,res){
count++;
console.log("why two?:" + count);
res.writeHead(200,{'Content-Type': 'text/html'});
if (req.url=='/') {
console.log(req.method);
console.log(req.headers);
console.log(req.url);
res.end('<marquee>Smashing Node</marquee>');
}
});
serv.listen(3000);
in this it checks only for the '/' url and then responds....so the marquee is returned

Related

Document is not defined on node.js - How can i import a variable from another .js file to node.js server?

Edit: Actually, my problem is "How to use "value" from selection.js in the server.js ? " I want to direct user to a searching page according to his/her choice .
i am new at web programming. I have server.js and a selection.js.
server.js is a node file, and my server is in it. selection.js is my item class changer. I am changing selected item's class with selection.js and i am trying to use this selected item from server.js. When i try below codes, i am taking this shit: Document is not defined on node.js
It is really painful. I am trying to solve it about hours. But, nothing!
Pls, help me :/
selection.js :
var iconContainer = document.getElementById('iconContainer');
var icon = iconContainer.getElementsByClassName("item");
for (var i = 0; i < icon.length; i++) {
icon[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
const btnSearch = document.querySelector("#btnSearch");
btnSearch.addEventListener("click", () => {
// get the active item's value
const value = document.querySelector(".item.active span").innerText;
console.log("value: ", value);
// do fetch
});
});
}
module.exports={searchPath: "/"+value};
server.js:
var fs = require('fs');
var express = require('express');
var app = express();
var path = require('path');
app.use('/public', express.static(path.join(__dirname, 'public')));
// '/' girdisi için index.html getirilecek.
app.get('/', function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
});
//---------------------------------------------------
// Server kuruyoruz.
var server = app.listen(8081,"127.0.0.1", function () {
var host = server.address().address;
var port = server.address().port;
console.log('Server http://' + host + ':' + port+' adresinde çalışıyor...');
});
var search = require('./public/js/selection');
console.log(search.searchPath);
So, the code you label as selection.js needs to be in your web page, either directly embedded or linked from a <script> tag so it can run in the web page in the browser.
Then, that code can make an Ajax call using the XMLHttpRequest or fetch() interfaces in the browser to a route on your server and pass the desired value.
That route on your server (which you need to define and add code for) can then examine that value and decide what data to return the the Ajax call.
Your Javascript in the web page, then receives that returned data from the Ajax call and decides what to do with it such as insert new content in the page for the user to see, cause the browser to load a different page or refresh the current page or whatever else is appropriate.

Trouble using GET for a json file in node js

I'm new to REST api's and javascript in general and I'm having trouble using GET to retrieve a json file and display it in a browser. I'm only running my api as a localhost for now. I can get my server running but just can't get my json file to display. Below is my code, I have tried different things with the responce but have had no luck with getting it to work. Everything I've tried with it has displayed errors. Both this file and the json file are in the same folder. If someone knows what I need to put for instead of the //responce() it would be greatly appreciated. Thanks!
var http = require('http');
var express = require('express');
var app = express();
var port = process.env.port || 3000;
app.listen(port, function(){
var datetime = new Date();
var message = "Server running on Port:- " + port + " Started at :- " +
datetime;
console.log(message);
});
app.get("/userget", function(request, responce){
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('database.json', 'utf8'));
//responce()
});
If you have your javascript object, try:
res.status(200).json({
your_javascript_object
});
Put this instead for your /userget route.
```
res.setHeader('Content-Type', 'application/json');
var fs = require('fs');
res.send(JSON.parse(fs.readFileSync('database.json', 'utf8')));
```

issue child process inside a server on node.js

I have an executable library in C (sudo ./ads1256_test adc.txt) where data are acquired from an ADC, likewise these data are automatically save in a text file (adc.txt).
On the other hand, I have a server in node.js (see code) in which would like to execute this program when a button in the website is pressed. For this, I tried to implement this process using the child process .exec('sudo ./ads1256_test adc.txt') but it did not work. It apparently runs but the values saved in the file are always zero. That is totally different to the obtained result when I execute the same command in terminal. I would appreciate if anybody could help me.
//Importing the core modules
var express = require('express');
var path = require('path');
var sys = require('sys');
var fs = require('fs');
var util = require('util');
var sleep = require('sleep');
var app = express();
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
app.get('/', function(req,res){
res.sendFile(path.join(__dirname + '/public/index.html'));
});
//Static Directories
app.use(express.static(__dirname + '/public'));
app.post('/test', function (req, res) {
exec('sudo ./ads1256_test adc.txt');
});
//Server Starting
var server = app.listen(8080, function(err){
if(err){
console.log('Error starting http server');
} else{
console.log('Sever running at http://localhost:8080 ');
}
});
first thing first, fix your code to
- asynchronously handle the cp spawn
- show errors
Example with tree, may you adapt it to your binary and check the response, it should help you go forward.
app.post('/test', function (req, res) {
var cp = spawn('tree', []);
cp.stdout.pipe(res);
cp.stderr.pipe(res);
cp.on('close', function () {
res.end();
cp.stdout.unpipe();
cp.stderr.unpipe();
});
});

(crypto.js) TypeError: Data must be string or buffer

I am currently using crypto.js module to hash things. It was working for a while then I started getting this error:
Here is the foundation of my server:
process.stdout.write('\033c'); // Clear the console on startup
var
express = require("express"),
app = express(),
http = require("http").Server(app),
io = require("socket.io")(http),
path = require("path"),
colorworks = require("colorworks").create(),
fs = require("fs"),
crypto = require("crypto");
function md5(msg){
return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
return crypto.createHash("sha256").update(msg).digest("base64");
}
http.listen(443, function(){
// Create the http server so it can be accessed via 127.0.0.1:443 in a web browser.
console.log("NJ project webserver is running on port 443.");
// Notify the console that the server is up and running
});
app.use(express.static(__dirname + "/public"));
app.get("/", function(request, response){
response.sendFile(__dirname + "/public/index.html");
});
I am aware that these functions are creating the problem:
function md5(msg){
return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
return crypto.createHash("sha256").update(msg).digest("base64");
}
The problem being, if these functions don't work (which they don't anymore), roughly 200 lines of code will go to waste.
This error is triggered by attempting to hash a variable that does not exist:
function md5(msg){
return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
return crypto.createHash("sha256").update(msg).digest("base64");
}
md5(non_existent); // This variable does not exist.
What kind of data are you trying to hash ? Where does it come from ?
I would check the value of msg first then I would try :
crypto.createHash('md5').update(msg.toString()).digest('hex');
You could also use these packages instead:
https://www.npmjs.com/package/md5
https://www.npmjs.com/package/js-sha256

Node js Error: Protocol "https:" not supported. Expected "http:"

I am using IBM Bluemix to make a web service for a school project.
My project needs to request a JSON from an API, so I can use the data it provides. I use the http get method for a data set, and I am not sure if it is working properly.
When I run my code, I get the message:
Error: Protocol "https:" not supported. Expected "http:"
What is causing it and how can I solve it?
Here is my .js file:
// Hello.
//
// This is JSHint, a tool that helps to detect errors and potential
// problems in your JavaScript code.
//
// To start, simply enter some JavaScript anywhere on this page. Your
// report will appear on the right side.
//
// Additionally, you can toggle specific options in the Configure
// menu.
function main() {
return 'Hello, World!';
}
main();/*eslint-env node*/
//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------
// HTTP request - duas alternativas
var http = require('http');
var request = require('request');
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
//chama o express, que abre o servidor
var express = require('express');
// create a new express server
var app = express();
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
});
app.get('/home1', function (req,res) {
http.get('http://developers.agenciaideias.com.br/cotacoes/json', function (res2) {
var body = '';
res2.on('data', function (chunk) {
body += chunk;
});
res2.on('end', function () {
var json = JSON.parse(body);
var CotacaoDolar = json["dolar"]["cotacao"];
var VariacaoDolar = json["dolar"]["variacao"];
var CotacaoEuro = json["euro"]["cotacao"];
var VariacaoEuro = json["euro"]["variacao"];
var Atualizacao = json["atualizacao"];
obj=req.query;
DolarUsuario=obj['dolar'];
RealUsuario=Number(obj['dolar'])*CotacaoDolar;
EuroUsuario=obj['euro'];
RealUsuario2=Number(obj['euro'])*CotacaoEuro;
Oi=1*VariacaoDolar;
Oi2=1*VariacaoEuro;
if (VariacaoDolar<0) {
recomend= "Recomenda-se, portanto, comprar dólares.";
}
else if (VariacaoDolar=0){
recomend="";
}
else {
recomend="Recomenda-se, portanto, vender dólares.";
}
if (VariacaoEuro<0) {
recomend2= "Recomenda-se, portanto, comprar euros.";
}
else if (VariacaoEuro=0){
recomend2="";
}
else {
recomend2="Recomenda-se,portanto, vender euros.";
}
res.render('cotacao_response.jade', {
'CotacaoDolar':CotacaoDolar,
'VariacaoDolar':VariacaoDolar,
'Atualizacao':Atualizacao,
'RealUsuario':RealUsuario,
'DolarUsuario':DolarUsuario,
'CotacaoEuro':CotacaoEuro,
'VariacaoEuro':VariacaoEuro,
'RealUsuario2':RealUsuario2,
'recomend':recomend,
'recomend2':recomend2,
'Oi':Oi,
'Oi2':Oi2
});
app.get('/home2', function (req,res) {
http.get('https://www.quandl.com/api/v3/datasets/BCB/432.json?api_key=d1HxqKq2esLRKDmZSHR2', function (res3) {
var body = '';
res3.on('data', function (chunk) {
body += chunk;
});
res3.on('end', function () {
var x=json.dataset.data[0][1];
console.log("My JSON is "+x); });
});
});
});
});
});
Here is a print of the error screen I get:
When you want to request an https resource, you need to use https.get, not http.get.
https://nodejs.org/api/https.html
As a side note to anyone looking for a solution from Google... make sure you are not using an http.Agent with an https request or you will get this error.
The reason for this error is that you are trying to call a HTTPS URI from a HTTP client. The ideal solution would have been for a generic module to figure out the URI protocol and take the decision to use HTTPS or HTTP internally.
The way I overcame this problem is by using the switching logic on my own.
Below is some code which did the switching for me.
var http = require('http');
var https = require('https');
// Setting http to be the default client to retrieve the URI.
var url = new URL("https://www.google.com")
var client = http; /* default client */
// You can use url.protocol as well
/*if (url.toString().indexOf("https") === 0){
client = https;
}*/
/* Enhancement : using the URL.protocol parameter
* the URL object , provides a parameter url.protocol that gives you
* the protocol value ( determined by the protocol ID before
* the ":" in the url.
* This makes it easier to determine the protocol, and to support other
* protocols like ftp , file etc)
*/
client = (url.protocol == "https:") ? https : client;
// Now the client is loaded with the correct Client to retrieve the URI.
var req = client.get(url, function(res){
// Do what you wanted to do with the response 'res'.
console.log(res);
});
Not sure why, but the issue for me happened after updating node to version 17, i was previously using version 12.
In my setup, i have node-fetch using HttpsProxyAgent as an agent in the options object.
options['agent'] = new HttpsProxyAgent(`http://${process.env.AWS_HTTP_PROXY}`)
response = await fetch(url, options)
Switching back to node 12 fixed the problem:
nvm use 12.18.3
I got this error while deploying the code.
INFO error=> TypeError [ERR_INVALID_PROTOCOL]: Protocol "https:" not supported. Expected "http:"
at new NodeError (node:internal/errors:372:5)
To fix this issue, I have updated the "https-proxy-agent" package version to "^5.0.0"
Now the error was gone and it's working for me.

Categories