I'm trying out the code basics and want to write some basic client-server app.
I have an HTML page where user inputs two numbers (num1 and num2) then it passes to JS which passes it to HTTP server written with NodeJS. On the server the numbers should be added and returned to the HTML page. But the server returns this error:
ReferenceError: num1 is not defined
What is wrong with the code?
Here is the JS code:
function myFunction(num1, num2) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
num1 = Math.floor(num1);
num2 = Math.floor(num2);
document.getElementById("result").innerHTML = this.responseText;
}
};
xhttp.open("GET", "http://localhost:8080?num1=2&num2=3", true);
xhttp.send();
}
And here is the NodeJS code:
var http = require('http');
http.createServer(function (req, res) {
var resnum = 2 + req.params(num1) + req.params(num2);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(resnum);
res.end();
}).listen(8080);
You have to use the url module https://nodejs.org/api/http.html#http_message_url
var http = require('http');
var url = require('url');
http.createServer(function (req, res) {
var params = url.parse(req.url, true).query;
var resnum = 2 + params.num1 + params.num2; //or 2 + parseInt(params.num1) + parseInt(params.num2)
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(resnum);
res.end();
}).listen(8080);
If you want a concise code like yours you need to use some module like Express framework.
var express = require('express')
var app = express()
app.get('/', function (req, res) {
const resnum = 2 + parseInt(req.query.num1) + parseInt(req.query.num2);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(resnum.toString())
})
app.listen(8080)
When you are using 'http' module only, the only thing you have to work with is req.url. You could try hard and get the parameters by breaking down the url but you would have a lengthy code:
var http = require('http');
http.createServer(function (req, res) {
const step1 = req.url.split('?')[1] //step1 = num1=2&num2=3
const step2 = step1.split('&') // step2 = [num1=2,num2=3]
let result = {};
step2.forEach((val) => { //break down strings further and put into result object
const value = val.split('=')
result[value[0]] = value[1]
})
var resnum = 2 + parseInt(result.num1) + parseInt(result.num2);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(resnum.toString());
}).listen(8080);
Some notes:
You get that error because num1 is a variable argument to a
function. However we don't have a variable num1 declared.
Parameters come as strings so unless you parse them into integers,
you will have string concatenation and 223 as a result
res.write and res.end need a
string input so you need to parse back to string after calculations.
Related
I a m kinda stuck. I made a request to a server. I want the server to computer a operation for me, and send me back the result.
Request :
ar http = require('http');
http.createServer(function(req, res){
var response = "Hello from " + req.client.remoteAddress + ":" + req.client.remotePort + "\n to " + req.client.localAddress + ":" + req.client.localPort;
console.log(response);
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const Http = new XMLHttpRequest();
console.log("start");
n = 15;
const urlfibo='http://172.22.0.4:8899';
Http.open("POST", urlfibo,false);
var params = 'value=15';
Http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
Http.send(params);
console.log(Http.responseText);
response += Http.responseText;
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(response);
res.end();
On my server, i don't know where to find the parameter i passed. I've tryed the solution in the doc, but my code is never running into it :
```
response += "\n ON" + req.on
let body = [];
req.on('data', (chunk) => {
response += "bla"
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
// at this point, `body` has the entire request body stored in it as a string
});
My question is : on y server (second part of code), how do i get my params i passed when i sent the request ? I want to do it with nodejs without using frameworks
Thank you
chunk will have all informations because is an object, you just have to assign this values for a new object and look for the parameters. Bug make sure to have in your code:
const bodyParser = require('body-parser');
app.use(bodyParser);
I'm trying to know how jsonp work, so I wrote a demo working on nodejs, without jQuery. But, it was not working.
Bellow was my code:
views/index.jade
doctype html
html
head
title Demo of jsonp
body
#result
script.
var xhr = new XMLHttpRequest();
var url = '/getjsonp?callback=abc'
function abc (data) {
alert('aaa')
document.getElementById('result').innerHTML = data.name;
}
xhr.open('GET', url);
xhr.send();
server.js
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
var data = { name: 'jacket', company: 'fdd' };
app.set('views', path.join(__dirname, 'views/'));
app.set('view engine', 'jade');
app.use(bodyParser.urlencoded({ extended: false }))
app.get('/', function (req, res, next) {
res.render('index');
});
app.get('/getjsonp', function (req, res, next) {
var callback = req.query.callback;
res.writeHead(200, { 'Content-Type': 'application/javascript' });
res.end(callback + '(' + JSON.stringify(data) + ')');
});
app.listen(3000);
And here is the response:
abc({"name":"jacket","company":"fdd"})
As my expect, I define a method abc() in index.jade, then request '/getjsonp?callback=abc' by async ajax, it'll response a javascript which will execute the method: abc().
But it was not working like that, I dont know anywhere was wrong, hope you can tell me if you know.
Thanks!
I believe that everything is working here, it's just that in the client, you'll need to retrieve the data sent back from the server using:
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
eval(xhr.responseText);
}
};
hope this helps :)
NOTE: eval will make a string like "abc({a: 'a'})" to running the function abc with a parameter with 1 argument (which is the object {a: 'a'}
And I found another way to make it work without ajax:
<script>
function abc (data) {
alert('aaa')
document.getElementById('result').innerHTML = data.name;
}
</script>
<script type="text/javascript" src="/getjsonp?callback=abc"></script>
Heads up: I am very new to Node.js, so this code might not be the best way to do it all. I am still in the learning process.
When I run the .JS file through node and go to the localhost:1337, all of the HTML shows up correctly, but the image does not render. when i look in the source code, the image is being brought in as Text/HTML and not an image.
Why is this? Is that why the image is not being displayed?
This is my code so far.
var http = require('http'),
fs = require('fs'),
request = require('request'),
url = require('url');
http.createServer(function (req, res)
{
console.log(req.url);
var request = url.parse(req.url, true),
action = request.pathname,
html = buildHtml(req);
res.writeHead(200, {'Content-Type': 'text/html','Content-Length': html.length,'Expires': new Date().toUTCString()});
res.end(html);
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
function buildHtml(req)
{
var header = "",
body = '<img src="../Dilbert.jpg" alt="Dilbert">';
return '<!DOCTYPE html>'
+ '<html><header>' + header + '</header><body>' + body + '</body></html>';
};
var download = function(uri, filename, callback)
{
request.head(uri, function(err, res, body)
{
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};
download('http://assets.amuniversal.com/145cd9c0fb4e0132ee37005056a9545d', 'Dilbert.jpg', function(){
console.log('done');
});
I'm new to node Js, I've build a really simple server that send me back a zip file I request. It's all working but after some request a crash occur and i visualize this message on the terminal :
FATAL ERROR: node::smalloc::Alloc(v8::Handle, size_t, v8::ExternalArrayType) Out Of Memory
var http = require('http');
var url = require('url');
var fs = require('fs');
var port = 1337;
// create http server
var server = http.createServer(function (request, response) {
var path = require('url').parse(request.url, true);
console.log('requested ' + path.pathname);
//get zipped resoures
if (path.pathname == '/getzip') {
console.log(request.url);
var queryData = url.parse(request.url, true).query;
if (queryData.name) {
var filename = queryData.name;
//open corrisponding file
var zipFile = fs.readFileSync('packets/' + filename);
response.writeHead(200, {
'Content-Type': 'application/x-zip',
'Content-disposition': 'attachment; filename=data.zip'
});
//send file in response
response.end(zipFile);
}
else {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('{error = "bad url"}');
}
}
}).listen(port);
server.timeout = 1000000;
Do you have any idea of what it can be? this code looks so simple.
Instead of reading the entire file into memory, you should leverage streams for this:
response.writeHead(200, {
'Content-Type' : 'application/x-zip',
'Content-disposition' : 'attachment; filename=data.zip'
});
fs.createReadStream('packets/' + filename).pipe(response);
I'm creating HTTP server and inside i'm sending a request to to yahoo finance website and getting some data from it, what i want to do is to print to browser the data i got from yahoo finance.
the thing is that response.write isn't working inside the request.
Here is my code:
var http = require('http');
var request = require('request');
var cheerio = require('cheerio');
var util = require('util');
var host = "127.0.0.1";
var port = 1400;
var server = http.createServer(function (req, res) {
//writing the headers of our response
res.writeHead(200, {'Content-Type':'text/plain'});
// Variable Deceleration
// TODO: move from the global scope
var ticker = "IBM";
var yUrl = "http://finance.yahoo.com/q/ks?s=" + ticker;
var keyStr = new Array();
//
// The main call to fetch the data, parse it and work on it.
//
request(yUrl, function (error, response, body) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(body);
// the keys - We get them from a certain class attribute
var span = $('.time_rtq_ticker>span');
stockValue = $(span).text();
res.write("trying to print something");
console.log("Stock - " + ticker + " --> text " + stockValue );
}
}); // -- end of request --
res.write('Welcome to StockWach\n');
//printing out back to the client the last line
res.end('end of demo');
});
server.listen(port, host, function () {
console.log("Listening : " + host +":" + port);
});
You have to end the response (res.end();). Almost all browsers buffer some number of bytes from the response before showing anything, so you won't see the trying to print something until the response has ended.
If you use something like cURL though, you will see the trying to print something right away before the response is ended.