Print received data from client in NodeJS server - javascript

I have a simple html file containing that piece of javascript:
<script type="text/javascript">
$.ajax({
url: 'http://192.168.X.X:8080',
data: '{"data": "1"}',
dataType: "jsonp",
cache: false,
timeout: 5000,
success: function(data) {
var ret = jQuery.parseJSON(data);
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
document.getElementById("error").innerHTML = 'Error: ' + error.message;
}
});
</script>
I simply want my NodeJS server to print data received (there: the number 1°).
Here is my NodeJS code:
var http = require('http');
var s = http.createServer();
s.on('request', function(request, response) {
response.writeHead(200);
console.log('a: '+request.method);
console.log('b: '+request.headers);
console.log('c: '+request.url);
});
s.listen(8080);
Server is receiving requests just find but how to retrieve the value of the data sent?
I just want server to receive a number from client and print it. How to do that?
Many thanks1

I think this does what your looking for.
#!/usr/bin/node
var http = require('http');
var s = http.createServer();
s.on('request', function(request, response) {
response.writeHead(200);
console.log('a: '+request.method);
console.log('b: '+request.headers);
console.log('c: '+request.url);
var url = decodeURIComponent(request.url);
var startPos = url.indexOf('{');
var endPos = url.indexOf('}');
var jsonString = url.substring(startPos, endPos+1);
json = JSON.parse(jsonString);
console.log(json['data'])
});
s.listen(8080);

If you just want to see jsonp works using the http module, you could use something like that (I wouldn't advise using this in any of your code, it's just for the demonstration):
var http = require('http');
var querystring = require('querystring');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var query = querystring.parse(req.url.split('?')[1]);
console.log(query);
res.end(query.callback + '({"Name": "Foo", "Id": 1234, "Rank": 7})');
}).listen(8080);
Note: when using jquery jsonp data should better be an object, not a string (see https://learn.jquery.com/ajax/working-with-jsonp/)
You should, however, ask yourself:
Why jsonp?
Is there a module that does all that for you & parse JSON, help you with errors/authentication/etc? I usually use https://www.npmjs.com/package/hapi (It supports jsonp if you really need it), there other modules like express.

Related

CryptoJs is not decrypting URL on my NodeJS server

I am forwarding API calls from my frontend to my backend. I encrypt the API calls using CryptoJS.AES using the passphrase 'somekey'.
My relevant client code is...
var host = 'http://localhost:3000'
$('.send-button').click(function(){
var request = $('.request-input').val();
var encryptedRequest = CryptoJS.AES.encrypt(request, 'somekey');
console.log(encryptedRequest.toString())
var decryptedRequest = CryptoJS.AES.decrypt(encryptedRequest, 'somekey');
console.log('Decrypted Request: ' + decryptedRequest.toString());
handleRequest(encryptedRequest.toString());
});
var handleRequest = function(request){
$.ajax({
type: "GET",
url: host + '/requests?call=' + request,
success: function(data) {
var rawJSON = JSON.stringify(data, null, 2);
editor.setValue(rawJSON);
},
dataType: 'json'
});
}
relevant server side code is...
var port = 3000;
var serverUrl = "127.0.0.1";
var http = require("http");
var path = require("path");
var fs = require("fs");
var express = require("express");
var CryptoJs = require("crypto-js");
var app = express();
app.get('/requests', function(req, res) {
console.log('REQUEST: ' + req);
var call = req.query.call;
console.log(call)
console.log("To send: " + CryptoJs.AES.decrypt(call, 'somekey'));
});
The problem I keep getting is that it that when I decrypt it it either doesn't get the original URL and instead returns a bunch of jibberish. An example of this is...
Encryption: U2FsdGVkX1/NRbZkyP60pPu3Cb9IcQ4b9n4zJkExp2LNR3O1EdEpqHLNACnYuatN
Decryption: 68747470733a2f2f6e6577736170692e6f72672f76312f61727469636c6573
OR... It just returns nothing and appears blank.
Ideally I would like something like this.
Encryption: U2FsdGVkX1/NRbZkyP60pPu3Cb9IcQ4b9n4zJkExp2LNR3O1EdEpqHLNACnYuatN
Decryption: https://newsapi.org/v1/articles
Can anyone see what I am dong wrong?
Here is a working jsfiddle:
https://jsfiddle.net/5Lr6z4zp/1/
The encryption results in a Base64 string, while the decrypted string is Hex. To get back the “Message” you need to convert that to Utf8: decryptedRequest.toString(CryptoJS.enc.Utf8)
Here is the relevant part of the code that works:
var request = "testing decryption";
var encryptedRequest = CryptoJS.AES.encrypt(request, 'somekey');
console.log(encryptedRequest)
var decryptedRequest = CryptoJS.AES.decrypt(encryptedRequest, 'somekey');
var decryptedMessage = decryptedRequest.toString(CryptoJS.enc.Utf8)
console.log('Decrypted Request: ' + decryptedMessage);
Here is a link for a resources that explains the encryption/decryption in more detail:
http://www.davidebarranca.com/2012/10/crypto-js-tutorial-cryptography-for-dummies/

Why doesn't my http request work for long JSON string?

var http = require('http');
var qhttp = require('q-io/http');
var formidable = require('formidable');
var categories;
qhttp.read("https://api.myjson.com/bins/509wa")
.then(function (json) {
categories = JSON.parse(json).categories;
})
.then(null, console.error);
module.exports.putCat = function(req, res){
var form = new formidable.IncomingForm();
form.parse(req, function(error, fields, files){
if(error){console.log(error)}
fields["catProd"] = [];
categories.push(fields);
var dataString = JSON.stringify({categories: categories});
console.log(dataString);
var options = {
host : "api.myjson.com",
path : "/bins/509wa.json",
method: "PUT",
headers: {"Content-Type": "application/json", "Content-Length": dataString.length}
};
function callback(response){
var body = "";
response.on('data', function(chunk){
body+=chunk;
});
response.on('end', function(){
console.log('Received data: '+body);
});
}
http.request(options, callback).write(dataString);
res.end();
});
};
screenshot
It works perfectly with something like JSON.stringify("hello":"world");. However, when I tried with my data that needs to be stored (which is much longer), it doesn't send anything to the API. Thanks in advance!
You have a race condition with the categories variable. If some external code calls putCat() quickly after loading the module, then the categories data may not be available yet.
If you have async module loading things to do, then you should probably expose a module constructor which returns a promise and you can then do the putCat() after that promise resolves.

Node.js - load data and then hit urls - async

I am new at node.js, so please be patient :)
What I need to do:
load from url Ids of users
Hit another url for every ID
What am I doing wrong?
var http = require('http');
var Client = require('node-rest-client').Client;
var client = new Client();
url = 'http://example.com/api/get-users';
client.get(url, function (data, response) {
if (data.status == 'OK') {
users = data.users;
users.forEach(function(item) {
newUrl = 'http://example.com/generateStats/' + item;
client.get(newUrl, function(data, response){
console.log(data);
});
});
}
});
The value of users is: [1,2,4,5,7,...]
Nothing in forEach is executing, why?
There is no status in data nor response so it never go inside the if block. To handle errors with node-rest-client, you have to listen to the error event:
var http = require('http');
var Client = require('node-rest-client').Client;
var client = new Client();
url = 'http://example.com/api/get-users';
client.get(url, function(data, response) {
// if there is an error, this function is not executed
var users = data.users;
users.forEach(function(item) {
newUrl = 'http://example.com/generateStats/' + item;
client.get(newUrl, function(data, response) {
console.log(data);
});
});
}).on('error', function(err) {
console.log('something is wrong: ' + err.code);
});
There is a response.statusCode though, it returns an http code like 200.
I think you need something like async
Check this answer: simplest-way-to-wait-some-asynchronous-tasks-complete-in-javascript

Express.js proxy pipe translate XML to JSON

For my front-end (angular) app, I need to connect to an external API, which does not support CORS.
So my way around this is to have a simple proxy in Node.JS / Express.JS to pass the requests. The additional benefit is that I can set my api-credentials at proxy level, and don't have to pass them to the front-end where the user might steal/abuse them.
This is all working perfectly.
Here's the code, for the record:
var request = require('request');
var config = require('./config');
var url = config.api.endpoint;
var uname = config.api.uname;
var pword = config.api.pword;
var headers = {
"Authorization" : 'Basic ' + new Buffer(uname + ':' + pword).toString('base64'),
"Accept" : "application/json"
};
exports.get = function(req, res) {
var api_url = url+req.url;
var r = request({url: api_url, headers: headers});
req.pipe(r).pipe(res);
};
The API-endpoint I have to use has XML as only output format. So I use xml2js on the front-end to convert the XML reponse to JSON.
This is also working great, but I would like to lighten the load for the client, and do the XML -> JSON parsing step on the server.
I assume I will have to create something like:
req.pipe(r).pipe(<convert_xml_to_json>).pipe(res);
But I don't have any idea how do create something like that.
So basically I'm looking to create an XML to JSON proxy as a layer on top of an already existing API.
There are a lot of questions on SO regarding "how do I make a proxy" and "how do I convert XML to JSON" but I couldn't find any that combine the two.
you need to use transform stream and for xml to json conversion you need some library i use this xml2json
..then u use it like this (simplified but it should work with request too)
var http = require('http');
var fs = require('fs');
var parser = require('xml2json');
var Transform = require('stream').Transform;
function xmlParser () {
var transform = new Transform();
transform._transform = function(chunk, encoding, done) {
chunk = parser.toJson(chunk.toString())
console.log(chunk);
this.push(chunk);
done();
};
transform.on('error', function (err) {
console.log(err);
});
return transform;
}
var server = http.createServer(function (req, res) {
var stream = fs.createReadStream(__dirname + '/data.xml');
stream.pipe(xmlParser()).pipe(res);
});
server.listen(8000);

How to do a simple read POST data in Node JS?

I've used this code to read the querystring ?name=Jeremy ...can anyone tell me how to do this with post data? also with json?
var http = require('http'), url = require('url');
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type":"text/plain"});
var urlObj = url.parse(request.url, true);
response.write("Hello " + urlObj.query["name"] + "!\n");
}).listen(8000);
thanks!
You have to handle data and end events of http.ServerRequest object. Example:
var util = require("util"),
http = require('http'),
url = require('url'),
qs = require('querystring');
...
// this is inside path which handles your HTTP POST method request
if(request.method === "POST") {
var data = "";
request.on("data", function(chunk) {
data += chunk;
});
request.on("end", function() {
util.log("raw: " + data);
var json = qs.parse(data);
util.log("json: " + json);
});
}
Here is an article on this topic with example (with too old version of node.js so it might not work, but the principle is the same).

Categories

Resources