Authentication in URL for javascript - javascript

I am trying to write a simple script to obtain JSON data but the target requires login information in the actual URL like so:
http://login:password#URL/theapi
It appears that when using either getJSON or straight ajax the login details get skipped though even when passed on. I get an 401 error in developer tools in Chrome where it's interesting that the link in the error, when clicked, will actually go through and get he JSON data in to the browser
Is there a way around this?

Is there a way around this?
Yes, while making the AJAX call, don't attach login:password in the url. Instead, add Authorization header with Base64 encoded value of login:password. This is how we can do using JQuery:
$.ajax({
type: "GET",
url: "https://domain.tld",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(login + ":" + password));
}
});

Related

How to get a json response from yaler

I create an account with yaler, to comunicate with my arduino yun. It works fine, and i'm able to switch on and off my leds.
Then i created a web page, with a button that calls an ajax function with GET method to yaler (yaler web server accept REST style on the URL)
$.ajax({
url: "http://RELAY_DOMAIN.try.yaler.net/arduino/digital/13/1",
dataType: "json",
success: function(msg){
var jsonStr = msg;
},
error: function(err){
alert(err.responseText);
}
});
This code seem to work fine, infact the led switches off and on, but i expect a json response in success function (msg) like this:
{
"command":"digital",
"pin":13,
"value":1,
"action":"write"
}
But i get an error (error function). I also tried to alert the err.responseText, but it is undefined....
How could i solve the issue? Any suggestions???
Thanks in advance....
If the Web page containing the above Ajax request is served from a different origin, you'll have to work around the same origin policy of your Web browser.
There are two ways to do this (based on http://forum.arduino.cc/index.php?topic=304804):
CORS, i.e. adding the header Access-Control-Allow-Origin: * to the Yun Web service
JSONP, i.e. getting the Yun to serve an additional JS function if requested by the Ajax call with a query parameter ?callback=?
CORS can probably be configured in the OpenWRT part of the Yun, while JSONP could be added to the Brige.ino code (which you seem to be using).
I had the same problem. I used JSONP to solve it. JSONP is JSON with padding. Basically means you send the JSON data with a sort of wrapper.
Instead of just the data you have to send a Java Script function and this is allowed by the internet.
So instead of your response being :
{"command":"digital","pin":13,"value":0,"action":"write"}
It should be:
showResult({command:"analog",pin:13,value:0,action:"write"});
I changed the yunYaler.ino to do this.
So for the html :
var url = 'http://try.yaler.net/realy-domain/analog/13/210';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'showResult',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.action);
},
error: function(e) {
console.log(e.message);
}
});
};
function showResult(show)
{
var str = "command = "+show.command;// you can do the others the same way.
alert (str);
}
My JSON is wrapped with a showResult() so its made JSONP and its the function I called in the callback.
Hope this helps. If CORS worked for you. Could you please put up how it worked here.

Cross Origin ajax "POST" request failing

I have a webservice(REST) running on localhost:8080, to call the webservice I use this jquery code:
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/user/register",
data: '{"name": "' + name + '","email": "' + email + '","password": "' + password + '"}',
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType(jsonMimeType);
}
},
dataType:"jsonp",
Accept : "application/json",
contentType: "application/json",
success: registerUser_success_callback,
error: registerUser_error_callback
});
When I try to call this javascript from the same domain(i.e. localhost:8080), it work just like a charm!. Here is the screen shot of the same:
But when I try to access the same from a different domain(i.e localhost:80), it fails, and surprisingly instead of a POST, it sends out a GET and I also get a log in my server's log file, saying that the GET method not supported for REST resource. Here is the screen of the same:
From what I have read on internet(especially here, great article!), cross domain request should first send out an OPTIONS request(which is cached for later usage.) What is going wrong in my case?
I have tried calling the rest service with same parameters using FireFox's plugin RESTClient, I was able call the rest service(POST method) successfully, so this mostly is the issue with ajax part.
Help me resolve this cors hell! and do lemme know if I need to share any more details on this.
PS: After #A. Wolff Suggested, I changed the data tyoe from jsonp to json, now my browser sends out OPTIONS, but after that it doesn't send the actual POST request!!!
Well, some more digging and I found the solution to this!
After the change A. Wolff suggested, browser was sending out an OPTIONS request and was receiving a 200 response, but after that actual POST request was not being sent to the server.
Problem was, if you send any specific headers, "Content-Type" in my case, server has to add that header in "Access-Control-Allow-Headers" field of the response(response of OPTIONS request). I changed my server side code to populate that field in the response header, and VOILA!
Hope this will be helpful to others, too!
Happy Coding.

Cross-domain issue with Jquery

I am trying to create a chrome extension which will look up the meaning of input vocabulary from this URL: http://hanviet.org/ajax.php?query=%E6%97%A5&methode=normal
I made an ajax call by using jquery but got an error because of the cross-domain issue: "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access". Ok, I guest that instead of make a request directly to the URL, I need to call it through a proxy pages as below:
$.get("/myproxy.php?query=日&methode=normal", function( data ) {
alert( "Load was performed." );
});
After doing a google search, there is another chrome extension named DHC to makes http request: https://www.sprintapi.com/dhcs.html. and It works perfectly!
I am wondering that does DHC tool also send a request through its proxy or there is another way to make a direct request that I dont know.
Thank you!
$.ajax({
type: "GET",
url: 'URL',
jsonp: 'callback',
dataType: 'jsonp',
data: {},
success: loginSuccess,
crossDomain: true,
error: ajaxFailed,
contentType: 'application/json',
async: false
});
function ajaxFailed(result) {
alert("Failed: " + result.status + ' ' + result.statusText);
}
function loginSuccess(data) {
alert('Result: ' + data.d);
}
If you use the developers tools of chrome on that site, on Network tab you will see that after pressing the sendbutton it loads the content from https://www.sprintapi.com/api/proxy, so yes, it should be using a proxy.
Even more, as you say the Access-Control-Allow-Origin would'nt let they did it on another way I think.

Sending data to server using get request header

I use jQuery to contact my REST service on server side. The URL looks like this:
http://bla.com/?userid=1,2,3,4,5,6...
The userid string could be very long and it could happen that the max url size will be exceeded.
I can't do a post request, so my question is, whether it would be a good solution to send the userid data within the header? Something like this:
$.ajax({
url: 'someurl',
headers:{'foo':'bar'},
complete: function() {
alert(this.headers.foo);
}
});
Would this be possible?
Thanks
Yes you can send header using Ajax request
$.ajax({
type: "GET",
beforeSend: function(request) {
request.setRequestHeader("Authority", authorizationToken);
},
url: "entities",
data: "json=" + escape(JSON.stringify(createRequestObject)),
processData: false,
success: function(msg) {
$("#results").append("The result =" + StringifyPretty(msg));
}
});
you can read more about header on jQuery AJAX page
Also check this example here
This is totally possible, alhough it would be advisable to just use POST, because it was meant to transfer lots of data.
Using headers is a workaround which results in the same results as POST; losing the ability to navigate forward and back without re-submitting (or re-sending headers in this case, will be impossible if the data is gone).

getting json string from web service

I have got a web service which gets list of users from an external system and returns as json. and I call that webservice via jquery ajax.; I have placed ajax code below
$.ajax({
type: "GET",
url: webMethod,
data:"",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(msg) {
alert(msg.d);
},
error: function(e) {
alert(e);
}
});
Even though, the output is in correct format, the output I get from jquery.ajax seems to be wrong. it returns big chunk of the data correctly, then adds "; (" and continues to show the output.
Basically, the output is ("around %75 of data");(rest of the data) which makes my json invalid. I am not sure whether it is related to the maxJasonLenght or not but I also set it to the maximum. there seems to be a limitation on how much data you can get from web service as if I add more data to that json, the break down point changes.
Sample Output
[{"UserName":"a.b","FullName":"a b"},{ Many other users},{"UserName":"c.d","FullName":"c d"},{"UserName":"e.f",);jsonp1364397526212("FullName":"e f"}, {"UserName":"g.h","FullName":"g f"},{other users}}
do you have any idea why I am having this issue?
Thanks
Do you set the crossDomain option to TRUE? If I'm not wrong, if you set the crossDomain option to TRUE, the response would be JSON-P.
Look at this post so you can figure out how to handle the response:
What is JSONP all about?
I hope it would help!

Categories

Resources