trouble decoding url in javascript - javascript

I am urlencoding a url string using php and then passing it via curl to a phantomjs script where I am trying to decode it using javascript.
I am starting with:
localhost:7788/hi there/how are you/
which gets turned into:
localhost:7788/hi+there%2Fhow+are+you
on the php side by the urlencode() function.
On the phantomjs side , I have:
// Create serever and listen port
server.listen(port, function(request, response) {
function urldecode(str) {
return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}
// Print some information Just for debbug
console.log("We got some requset !!!");
console.log("request method: ", request.method); // request.method POST or GET
console.log("Get params: ", request.url); //
url= urldecode(request.url);
//-- Split requested params
var requestparams = request.url.split('/');
console.log(urldecode(requestparams[1]));
console.log(urldecode(requestparams[2]));
The output at the console is :
.....
request method: GET
Get params: /hi%2Bthere/how%2Bare%2Byou
hi+there
how+are+you
Why are the '+' signs not replaced with spaces? I'm trying to get rid of them and it looks to me that the function 'urldecode' should do this.

You should use rawurlencode() instead of urlencode() in the PHP side, so spaces are encoded with %20 and not+ signs, so javascript can decode them well with decodeURIComponent().

Related

Send file via Post using new SDK Firefox Addon

I'm searching to send a zip file to a server using the "Request" class from the new Firefox SDK for addons. This is my code:
var Request = require("sdk/request").Request;
var file = new FileUtils.File(pathToZipFile);
Request({
url: serverURL,
content: file,
onComplete: function (response) {
for (var headerName in response.headers) {
console.log(headerName + " : " + response.headers[headerName]);
}
console.log("Response " + response.text );
}
}).post();
But the error is:
[Exception... "Component returned failure code: 0x80520009 (NS_ERROR_FILE_INVALID_PATH) [nsILocalFile.target]" nsresult: "0x80520009 (NS_ERROR_FILE_INVALID_PATH)" location: "JS frame :: resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/commonjs/sdk/querystring.js :: stringify/< :: line 70" data: no]
I have tried to do some checks and:
The server is on and receives normal GET and POST without files
The zip file is present and the path is right
Do you see any errors?
Thanks a lot
The only way to do it with the Request module is to base a base64 encoded string to the content key. If you don't use this, then you can send data such as a Blob or DOMFile (new File()) instance.
But as we see in the SDK code, the request module sends the data variable on request (if its not a HEAD or GET request).
https://github.com/mozilla/addon-sdk/blob/master/lib/sdk/request.js#L110
The data var is made by running stringify on anything passed to the content key:
https://github.com/mozilla/addon-sdk/blob/master/lib/sdk/request.js#L76
Stringify makes it a string:
https://github.com/mozilla/addon-sdk/blob/f5fab7b242121dccfa4e55ac80489899bb9f2a41/lib/sdk/querystring.js#L30
So you have to send base64 encoded string. Or a binary string. Which sucks.
You can use the sdk/io module to read the file as an ArrayBuffer and then turn that ArrayBuffer into a base64 string or binary string.
This shows how to get a binary string: https://stackoverflow.com/a/16365505/1828637

Passing a parameter to a python function from javascript?

I'm trying to use Parse Cloud Code to run a python script. I'm passing a parameter, but I seem to be getting an error. I'm not 100% sure what the problem is, but it seems like I'm not composing the url correctly. Any help would be appreciated.
My python code looks like this:
# a function that makes a sentence more exciting
def excited(sentence):
return sentence + '!!!'
Here's my code in main.js:
Parse.Cloud.define('testFunction', function(request, response) {
var someParam = request.params['testString'];
var url = 'http://mywebsite.com/test.py/excited&sentence=' + someParam;
Parse.Cloud.httpRequest({
url: url,
success: function(httpResponse) {
console.log(httpResponse.headers);
console.log(httpResponse.text);
response.success();
}, error: function(httpResponse, error) {
console.error('Request failed with response code ' + httpResponse.status);
}
});
});
EDITED:
Now I understand the problem better.
You are trying to call a python method from Parse.Cloud javascript based service. Based on their tutorials, I think you probably wanted the other way round.
Parse.Cloud allows you to deploy some server-side code in javascript. Then you can make REST API calls from your mobile app to the server endpoints by using either python or curl or any other language or tool. While testing, you can just call the end points from python on your box.
So your server code (in cloud/main.js) should look like this:
Parse.Cloud.define("testFunction", function(request, response) {
var excitedSentence = request.params.testString + "!!!";
response.success(excitedSentence);
});
This code creates a REST API endpoint at https://api.parse.com/1/functions/testFunction
Then you can call this API endpoint by using python (assuming you have Python installed on your box):
import json,httplib
connection = httplib.HTTPSConnection('api.parse.com', 443)
connection.connect()
connection.request('POST', '/1/functions/testFunction', json.dumps({
"testString": "This is an example sentence"
}), {
"X-Parse-Application-Id": "xxxxx_PUT_YOUR_ID_xxxxxxx",
"X-Parse-REST-API-Key": "xxxxxxxx_YOUR_KEY_xxxxxx",
"Content-Type": "application/json"
})
result = json.loads(connection.getresponse().read())
print result
If you don't have python installed, you can call the API endpoint by going to the online dashboard.
Go to: Your App -> Core tab -> API Console.
For endpoint, select post (this is important), and specify "functions/testFunction" in the text box.
In request body, specify: {"testString" : "This is an example sentence"}
Click "Send Request" and you should see the following output:
"result": "This is an example sentence!!!"

NodeJS beginner : Fetching data from other URL using Requestify

I am a newbie in NodeJs and i have to shift my code igniter server api's to node js .
I am using requestify to fetch all the data from a webservice and once this is achieved i will
call insert method to save all the entries.
Following is my code which i am using :-
requestify.get('SERVER_URL_CODE_IGNITER_API')
.then(function(response) {
// This one works but gives me all the json element with a backward slash like
// containing escaping character . Which i dont want
res.jsonp(response.body);
// When using following line i get an error
// Error: getaddrinfo ENOTFOUND] code: 'ENOTFOUND', errno: 'ENOTFOUND',
// syscall: 'getaddrinfo
// response.getBody();
}
);
My understanding is that response.getBody() should work and give the desired result without
escape characters but i am not able to get that working while response.body works but gives
me all the server data with backward slashes like this :-
"[{\"id\":\"212\",\"uid\":\"304\",\"fromLat\":\"28.5962491\",\"fromLon\":\"77.3396212\",\"toLat\":\"28.4594965\",\"toLon\":\"77.0266383\",\"fromName\":\"Sector 12, Noida, Uttar Pradesh, India\",\"toName\":\"Gurgaon, Haryana, India\",\"startTime\":\"08:00 Hrs\",\"returnTime\":\"06:40 Hrs\",\"carModel\":\"suzuki baleno\",\"fuelType\":\"CNG\",\"chargePrice\":\"\",\"smoking\":\"Doesnt Matter\",\"name\":\"Ankur Gupta\",\"image\":\"http:\/\/graph.facebook.com\/100000725036031\/picture?type=large\",\"email\":\"ankur1040#gmail.com\",\"fbid\":\"100000725036031\",\"age\":\"0\",\"sex\":\"0\",\"regid\":\"abc\",\"points\":\"0\",\"contact\":\"9711778805\"}]"
When you are using response.getBody(); you are not sending response to the client. I guess you are trying to send the response to the client. You will need to do
res.jsonp(response.getBody());
response.body only gives you raw response body. you can do
console.log(response.body);
and
console.log(response.getBody());
to compare your output.
I am guessing you are using express framework?
your request handler should look like this
function(req, res){
//other codes
requestify.get('SERVER_URL_CODE_IGNITER_API')
.then(function(response) {
res.jsonp(response.getBody());
});
}

Node.js ignores all querystring parameters except the first one

I can't persuade Node.js to see the second parameter from my URL:
http://localhost:8888/cities?tag=123&date=2013-03-30T10:00:28.000%2B02:00
I start the Node.js server with the following command:
node --debug ./router_rest.js
I have the following code in my "router_rest.js" file:
require("http").createServer(function (req, res) {
// For PUT/POST methods, wait until the
// complete request body has been read.
if (req.method==="POST" || req.method==="PUT") {
var body = "";
req.on("data", function(data){
body += data;
})
req.on("end", function(){
return routeCall(req, res, body);
})
} else {
return routeCall(req, res, "");
}
}).listen(8888);
I make the following call from the command line:
curl http://localhost:8888/cities?tag=123&date=2013-03-30T10:00:28.000%2B02:00
When I debug and examine the 'req' parameter (in the anonymous function above), the url property appears as:
/cities?tag=123
I was expecting the url reported to be:
/cities?tag=123&date=2013-03-30T10:00:28.000%2B02:00
Even when I switch parameters, node still only sees the first one.
Why has the last parameter (ie. date) been truncated?
Node is fine.
The first ampersand in your curl command is causing the shell to run curl in the background. Add quotes around the URL and it will work.
curl "http://localhost:8888/cities?tag=123&date=2013-03-30T10:00:28.000%2B02:00"

XHR in Chrome Extension with CI

I'm sending a POST from a chrome extension content script to a server I control. I setup the permissions in the manifest ok. Here is my XHR code. (I want to avoid jQuery for this). Its sending an empty responseText
var xhr = new XMLHttpRequest();
xhr.open("POST",'http://mysite.com/make',true);
xhr.onreadystatechange=function() {
if (xhr.readyState == 4) {
var res = JSON.parse(xhr.responseText);
console.log(res);
}
}
xhr.send({'textbox':data[0].user,'from':'extension'});
data[0].user is an object I got directly from the Twitter API
in my CI controller I have
$user = $this->input->get_post('textbox', TRUE);
$from = $this->input->get_post('from', TRUE);
$fullURL = 'http://www.google.com'; //example of a URL from code.
$json = $this->output->set_content_type('application/json');
$json->set_output(json_encode(array('URL' => $fullURL)));
The response text is empty
a jquery call on the other hand works fine
$.post("http://mysite.com/make", { 'textbox': data[0].user, 'from':'jquery' },
function(data) {
console.log(data);
});
Reason is simple, JQuery post method can accept JSON and then convert it to string and send to the server.
What you are trying to do is to directly send JSON here :
xhr.send({'textbox':data[0].user,'from':'extension'}) // Incorrect way
send method should either accept NULL or a string which is generally made up of QueryString Parameters like.
xhr.send("textbox="+ data[0].user + "&from=extension"); // Correct way
This will ensure that your data goes to the appropriate URL with textbox and from as post request parameters.
and queryString will be generated like textbox=username1234&from=extension in the packet's body unlike one goes in Get with the headers along side the URL.
jQuery's post method makes it simpler for you to format data you send using JSON and then internally it converts that to a queryString to send parameters.
You can't directly send Javascript object like that with an XHR object!
Also checkout this example:
http://beradrian.wordpress.com/2007/07/19/passing-post-parameters-with-ajax/

Categories