Phantomjs script stops execution after json object parsing - javascript

I'm trying to pass post data to the following phantomjs script (using php/curl):
server.listen(port, function(request, response) {
// Print some information Just for debug
console.log("request method: ", request.method); // request.method POST or GET
if(request.method == 'POST' ){
console.log("POST params should be next: ");
console.log(request.headers);
code = response.statusCode = 200;
response.write(code);
console.log("POST params: ",request.postRaw);
console.log("POST params: ",JSON.stringify(request.postRaw));
var json = request.postRaw;
obj = JSON.parse(json);
console.log(obj.email);
console.log(obj.pass);
var userName = json.stringify(obj.email);
var userPass = json.stringify(obj.pass);
console.log("I'm here");
I am trying to parse out the username and password from the post request. I notice that if I leave in:
var userName = json.stringify(obj.email);
var userPass = json.stringify(obj.pass);
the script will hang after:
console.log("I'm here");
If I remove these 2 lines the entire script will execute normally. Why is this happening? How can I fix this so I can parse the json object (obj), but the script will not hang?

In regular javascript, JSON is capitalized (and case-sensitive). Not sure how PhantomJS' subset of javascript lines up with regular javascript, but it'd be my guess that you should probably use capital-case JSON there too.
So for example:
JSON.stringify(obj.email);

Related

CCDS Data Source Script will not log string

I have a script that runs when I click a "Test Connection" button in an Adaptive Insights Integration script. I am trying to log the XML that is returned, just to verify the information prior to coding the next part. The script I have is as follows:
function testConnection(context) {
// dataSource variable to get Data Source Setting Parameters
var dataSource = context.getDataSource();
// Get the static credentials parameters.
const userName = dataSource.getSetting("Adaptive Username").getValue(); // Not Nedeed after WD User Sync. Do Not delete
const password = dataSource.getSetting("Adaptive Password").getValue(); // Not Nedeed after WD User Sync. Do Not delete
const instanceCode = dataSource.getSetting("instanceCode").getValue();
//This example connects to Postman Echo using POST
var url = 'https://api.adaptiveinsights.com/api/v35';
var method = 'POST';
// XML request body, this is where the method type (ie. exportUsers) goes.
var body = '<?xml version="1.0" encoding="UTF-8"?><call method="exportUsers" callerName="AdaptiveInsightsAPI">'
body += '<credentials login="' + userName + '" password="' + password + '" /></call>';
var headers = { 'Content-Type': 'application/xml' };
var response = null;
let finalResponse = null;
try {
response = ai.https.request(url, method, body, headers);
finalResponse = response.getBody();
ai.log.logVerbose("API Call Successful", finalResponse);
return true;
}
catch (exception) {
ai.log.logInfo('api call failed', '' + exception);
return false;
}
}
The response will not show in the log, it only shows "...". However, if I change "finalResponse" to "finalResponse[1]" or try to log any other character from the string ([2],[3],[4],etc.), it displays the character in the string. I also tried to slice the characters to fit within the 1000 character limit, but that displays nothing at all when I try to log the response.
What can I do different to get the response body into the log?

How to handle JSON data from XMLHttpRequest POST, using nodeJS

Overarching goal is to save some JSON data I create on a webpage to my files locally. I am definitely sending something to the server, but not in format I seem to able to access.
JsonData looks like:
{MetaData: {Stock: "UTX", Analysis: "LinearTrend2"}
Projections: [2018-10-12: 127.62, 2018-10-11: 126.36000000000001, 2018-10-10: 132.17, 2018-10-09: 140.12, 2018-10-08: 137.73000000000002, …]}
XMLHttpRequest on my webpage:
function UpdateBackTestJSON(JsonUpdate){ //JsonUpdate being the JSON object from above
var request = new XMLHttpRequest();
request.open('POST', 'UpdateBackTestJSON');
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
request.onload = function() {
console.log("Updated JSON File");
};
console.log("about to send request");
console.log(JsonUpdate);
request.send(JSON.stringify(JsonUpdate));
}
and I handle posts on my server (rather carelessly I realize, just going for functionality as a start here)
var http = require('http')
, fs = require('fs')
, url = require('url')
, port = 8008;
var server = http.createServer (function (req, res) {
var uri = url.parse(req.url)
var qs = require('querystring');
if (req.method == 'POST'){
var body = '';
req.on('data', function (data){
body += data;
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6){
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
req.connection.destroy();
}
});
req.on('end', function () {
var POST = qs.parse(body);
console.log(POST); // PARSED POST IS NOT THE RIGHT FORMAT... or something, idk whats going on
UpdateBackTestData(POST);
});
}
function UpdateBackTestData(TheJsonData){
console.log("UpdateBackTestData");
console.log(TheJsonData);
JsonUpdate = JSON.parse(TheJsonData);
console.log(JsonUpdate["MetaData"]);
//var Stock = JsonUpdate["MetaData"]["Stock"];
// var Analysis = JsonUpdate["MetaData"]["Analysis"];
fs.writeFile("/public/BackTestData/"+Analysis+"/"+Stock+".json", TheJsonData, function(err){
if(err){
console.log(err);
}
console.log("updated BackTest JSON!!!");
});
}
Most confusing to me is that when I run this, the Json object Im am trying to pass, does go through to the server, but the entirety of the data is a string used as a key for a blank value in an object. when I parse the body of the POST, I get: {'{MetaData:{'Stock':'UTX','Analysis:'LinearTrend2'},'Projections':[...]}': ''}. So my data is there... but not in a practical format.
I would prefer not to use express or other server tools, as I have a fair amount of other services set up in my server that I don't want to go back and change if I can avoid it.
Thanks for any help

JSON url parse returns NaN in Node.js

I have created a URL Shortener web service, which returns JSON, if correct parameters (url) is passed.
Now, since I am learning Node.js, I am trying to create a Node.js wrapper for parsing the data and printing them in console (for now).
I am using http and request module for parsing the JSON data which I received from the url response.
This is my code that prints the data :
var request = require('request');
var http = require('http');
var url = process.argv[2];
var apiUrl = "http://shtr.ml/stats-api.php?url=" + url;
http.get(apiUrl,function(res){
var body = '';
res.on('data',function(chunk)
{
body += chunk;
});
res.on('end',function(){
const resp = JSON.parse(body);
console.log(JSON.stringify(resp));
if(resp.message.toString() == "Success")
{
console.log("Short URL : ",resp.short-url);
console.log("Long URL : ",resp.long-url);
console.log("Creation Date : ",resp.created);
console.log("Total Clicks : ",resp.clicks);
}
else
{
console.log("Stats Error !!");
}
});
}).on('error',function(e){
console.log("Got an error ",e);
});
Now, following is my code output :
C:\node-shtr-module>node index.js http://shtr.ml/ZVFWdk
{"message":"Success","short-url":"http://shtr.ml/ZVFWdk","long-url":"https://github.com/beingadityak/dot-net-mysql","created":"2016-09-27 22:58:06","clicks":"21"}
Short URL : NaN
Long URL : NaN
Creation Date : 2016-09-27 22:58:06
Total Clicks : 21
Why is the resp.short-url returning NaN even though the JSON contains the URL ? Please help.
As always, thanks in advance.
access it using
resp['short-url'] and resp['long-url']

Http request document head

I need to get the document title.
so I try to send request, and paser the response html to get title.
example (via nodejs module request):
request.get("http://www.google.com", function(err, res, body) {
var title = body.match(/<title>(.*?)</title>/g)[1];
})
but when the document is particularly large. the request is slowly.
Is there a way to get document title quickly? Please suggest. Thanks.
Request can give you stream of decompressed data as it is received: http://github.com/request/request#examples (2nd example)
You could keep appending the data received in a buffer, and checking whether it has your desired content yet ("</title>"). As soon as you get it, you could get your title and ignore the rest of the buffer in the stream.
var request = require('request');
var buffer = '';
var flag = 0;
request({
method: 'GET',
uri: 'http://www.google.com',
gzip: true
}).on('data', function(data) {
if (buffer.indexOf('</title>') == -1)
buffer += data;
else done();
});
function done() {
if (flag) return;
flag++;
var title = buffer.match(/<title>(.*?)<\/title>/)[1];
console.log(title);
}

Node.JS where to put the response.end()

I'm developing a simple NODE.JS application. First I create an httpServer using http module. Then I route the request to the requestsHandlers.js page. 'Response' parameter cames from the creation of the httpServer. Process1, process2 and process3 should write an answer to the page. This is the objective of this app, that process1, process2 and process3 write its respective text.
requestHandlers.js
var process1 = require("./process1");
var process2 = require("./process2");
var process3 = require("./process3");
function iniciar(response) {
console.log("Manipulador de petición 'iniciar' fue llamado.");
response.writeHead(200, {"Content-Type": "text/html"});
process1.fc1(response);
process2.fc2(response);
process3.fc3(response);
//response.end() //WHERE DO I PLACE IT?
}
As you can see, the response parameter is passed to process1.js, which after parsing some data shoud echo some information.
process1.js
var request = require('request')
function fc1 (response){
var url = 'http://webpagethatreturnsJSONfile.com/'
//Download webpage data and parses it
request(url, function(err, resp, body) {
if (err)
throw err;
var jsonResult = JSON.parse(body);
response.write("Number:" + jsonResult.number + '');
//response.end() //WHERE DO I PLACE IT?
});
}
exports.fc1 = fc1;
The point is that I don't know where to put 'response.end()'. Each process takes some time and I want to 'end' when all processes have echo their text.
How could I do it?
I don't know if the code I've attached is enough for helping me.

Categories

Resources