cherrypy/jquery CORS trouble - javascript

I've got a simple python web server based on cherrypy. Its resources shall provide an API. THe server has the following code to provide CORS:
def CORS():
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
if __name__ == "__main__":
cherrypy.tools.CORS = cherrypy.Tool('before_finalize', CORS)
cherrypy.quickstart(PyCachedAdmin(), config={'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}})
the server is running on localhost:8080. Now I've got a HTML file, available on localhost (default port 80) which loads jquery 1.9. I open the browser console to try the $.ajax to execute any AJAX request to the cherrypy server. I've been trying:
$.ajax({
url:'http://localhost:8080/',
type: "POST",
dataType: "json",
data: {command:"version"}
}).done(function(){
console.log('hej');
});
and
$.ajax({
url:'http://localhost:8080/',
type: "POST",
crossDomain: true,
dataType: "jsonp",
data: {command:"version"}
}).done(function(){
console.log('hej');
});
and
$.support.cors = true
and nothing worked. I'm getting either XMLHttpRequest cannot load http://localhost:8080/. Origin http://localhost is not allowed by Access-Control-Allow-Origin. or GET http://localhost:8080/?callback=jQuery19102827550224028528_1382823727186&command=version&_=1382823727187 404 (Not Found) when using jsonp (it's mysterious that it sends GET instead of POST). There is a few similar questions around, I tried them and these are my results (that something is still wrong).
PS the server is perfectly ok, since all curl tests pass. Something is wrong with the cross-domain stuff.

Are you activating the CORS tool?. You can use the tool by decorating the calling methods or set it on the configuration.
Given that the implementation of PyCachedAdmin is no expressed on the question I might guess that probably you are not enabling the tool, to do so you just need to change the config dictionary and make something like this:
cherrypy.quickstart(PyCachedAdmin(),
config={
'/': {
'request.dispatch':
cherrypy.dispatch.MethodDispatcher(),
'tools.CORS.on': True}})
Or if the methods that you are using on PyCacheAdmin has already been decorated or using _cp_config that extra configuration is not required and this answers will not help you.

Related

Looking for clarification; How do I access a particular webservice with local files an Ajax

It could be I have completely misunderstood how web services work.
So there's a webservice I want to access through a javascript file sitting in a folder on my desktop. The server I am trying to access has not set a CORS header, so I have some trouble just using regular ol' ajax.
And frankly I am not sure where to go from here.
$.ajax({
type:"get",
crossdomain: "true",
url: "https://name", //actual name redacted from this question
success: function(data){
console.log(data);
}
});
A regular get like this will print the following in firefox's console.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ws.zooom.no/v1/channels. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
I got a hint from the task giver that I need to set the following in my "hosts file"
#127.0.0.1 www.domainname.com
Which confuses me. I have little to no experiences hosting anything, but does this hint that I need to maybe virtually host my "webpage" to access the webservice? It probably doesn't help to say I feel at a loss here.
So the bad news is that unless the 3rd party service either allows cross-domain requests (this is a configuration on that 3rd party server), or allows JSONP requests, you really have no option to access this service using a browser and javascript.
You could perhaps build your own service to proxy requests to that third party service. This would give you control over domain, CORS, JSONP, etc.
I found a solution.
Using something called "JSONP" that I had never heard of until now, i wrote a request like this
$.ajax({
type: 'GET',
url: "https://DOMAINNAME.com",
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data)
},
error: function(e) {
console.log(e.message);
}
});
This somehow completely negated the CORS problems

Cross-domain GET request, difference between browser and localhost making the call

I attempt to make a GET request to an API from a locally hosted meteor app (=> App running at: http://localhost:3000/) and upon doing so I get the error:
"XMLHttpRequest cannot load [the-api-url]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin http://localhost:3000 is therefore not allowed access."
Yet when I paste [the-api-url] into my browser and hit ENTER, the appropriate API response is shown in my browser window (a little JSON object). I have read some other SO posts about cross-domain request issues, but I don't understand the solutions, or what the difference is between sending the GET from my code or from the browser. Can someone explain why this behavior occurs, and what the appropriate change to my code/design is? My existing code is as below:
$.ajax({
type: "get",
url: auth_ad_act_url,
data: {
ads_token: ACCESS_TOKEN
},
dataType: 'jsonp',
success: function(data, status) {
console.log(data);
}
});
EDIT:
I do a jQuery.ajax() of type "get" supplied with a URL, parameters object, and success callback function, and dataType 'jsonp' to deal with cross-domain requesting.
I posted new code. Now the error is that the response is not correct. (I know this because it worked from my browser, and that responsee lined up with the API documentation). The response is "Resource interpreted as Script but transferred with MIME type text/html: https://host.com/apps/[my-app-id]/authorize_ad_account?callbac…" but it should be an object with the key 'url' and one other thing. I also get the error "Uncaught SyntaxError: Unexpected token :" when I include 'jsonp'. But that incorrect response mentioned above still gets logged to console so I don't understand when that syntax error happens, or where.
The Same Origin Policy does not include what you type into your address bar. If it did, you literally would not be able to access any website at all unless it was saved on your local machine!
In your situation, in order to get the resource that you need from jQuery's get, you'll either need to use a server-side proxy hosted on a matching domain, or since you're consuming JSON see if the API you're using supports JSONP.
There is a possibility to get JSON Data with a cross-domain request. You have to use JSONP and define a callback method, which has to be in the call and in the JSON Data.
Your request:
$.ajax({
type: "GET",
url: auth_ad_act_url + "&callback=?",
jsonpCallback: "jsonCallback",
dataType: "jsonp",
success: function(data) {
// Do something with the data
}
)};
The JSON File on the external server:
jsonCallback(INSERT_HERE_THE_JSON_DATA);
If you do not have the possibility to add the jsonCallback on the external server, check out CORS.

How to get data from MongoDB on client side using javascript/jQuery

I have written a code in bottle in python which gets data from mongodb and when the user request the url http://localhost:8080/index/test from bottle it will return the json result from mongoDB. it works fine when I point my browser to that url, I can see all the result on the browser.
However when I try to send a request from jQuery ajax I always get error, and the request never succeeds.
Has anyone ever done anything similar who can share their approach with me?
MY general question is, what the best way to get data from MongoDB from client side, when using bottle as the server. I have seen some example in Node.js but I want to use python as the server.
I have used this code.
$.ajax({
type: "POST",
url: "http://localhost:8080/hello/test",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log("success");
},
error: function (response){
console.log("failed");
}
});*/
And I have also tried this :
$.post( "http://localhost:8080/hello/test", d)
.done(function( response ) {
console.log("success");
});
no luck with any of these. I have also tried GET instead of post, but no luck.
This is kind of what I have in python side :
from bottle import route, run, template
#route('/hello/<name>')
def index(name):
return {'status':'online', 'something':'blah blah'}
run(host='localhost', port=8080)
Many thanks in advance.
First of all 'GET' is the better alternative since you are not passing any params to your DB.
Secondly on which port is your application running? You are adding 8080 to your request which lets me assume your app is running under a different port. JS is based on the Same Origin Policy that means if you want to access data from a different URL (different port = different url) it won't give you any repsponse data.
To make this work either make sure the python script is passing the information to your application directly or you have to implement Cross Origin Ressource Sharing.
To do this you have to add a header to the response of your python (port 8080) script with the following content
Access-Control-Allow-Origin: localhost:XXXX //replace XXXX with your application port
EDIT:
If you need to know how to activate COR check out this thread on stackoverflow:
PY Bottle enable COR

How can I run ajax code without web server?

I am running ajax without a server on my system, I have created one index.html with this.
JavaScript function:
function do_the_click(url)
{
alert('inside this method do_the_click');
$.ajax({
async: false,
url : url,
contentType: "text/html",
type : "GET",
dataType : "text/html",
success: function(data){
alert('data');
}});
}
My HTML body content is:
<a href="Java Collections.html" class="button" id="javacollections" onclick="do_the_click('this.href');"/>Java Collections</a>
I'm able to get the this message in alert window inside this method do_the_click but am not able to get the data in alert window, and so not able to get the page Java Collections.html in the index.html,
I have searched very much on Google re. how to load the data locally without using server in jquery.ajax but I didn't find any good solution, so I think that its good for others as well if it resides on Stack overflow.
You cannot do such thing. if you dont have a server you cannot send ajax it will be a cross browser issue. as the others says ajax will not work with file:// protocol you need a server to make an http:// call that ajax supports.
When you are making AJAX requests using stand alone html files, the HTTP request to the url is made by the browser. All you need to make sure is that you have included JQuery. Here is what you have to do.
Include Jquery:
<script src="js/jquery-1.10.2.min.js"></script>
The JQuery here resides in the js folder. This is included in the stand alone html file. Now to make the AJAX request use the following code.
$.ajax({
type: 'GET',
url: url,
success: function(data){
console.log(data);
},
async:false
});
AJAX creates an HTTP request that must be responded to by a server. If you don't have a server you can't use an AJAX request. You can run a server on your computer, but this is not the same as getting a file from the local filesystem.
I m able to run the ajax without webserver the problem was with my code the code written below that i had run on my filesystem u can use that as well.
function do_the_click(brl)
{
alert('inside this method do_the_click');
alert(brl);
var request = $.ajax({
async: false,
url: brl,
contentType: "text/html",
type : "GET",
dataType : "html",
});
request.done(function( msg ) {
alert(msg);
$( "#contentarea" ).load( msg, function() {
alert( "Load was performed." );
});
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
Java Collections
You won't be able to do this. If you don't have a server, you will violate the browser's cross-domain policy, as you won't have a domain!
AJAX won't work via the filesystem, you need a server.
This is an older thread but a browser doesn't need to run on a common OS like OSX/Windows/etc .. many people today are making their own browsers from WPE/Wayland or QT5Webkit where same origin policies don't apply.
Now in current scenario it depends upon where your server at. If the server is some place else, it will require CORS (cross origin request). So using file:// with CORS works perfectly.
I came to this question because I was searching for the reason, why I am able to make ajax request without using a web server. Got the answer Thanks!

Trouble performing simple GET request returning JSON with Javascript

I'm horrible at Javascript, so sorry in advance for what I'm going to go ahead and assume is an amazingly stupid question.
I'm simply trying to perform a GET request to GitHub's public repo API for a given user, and return the value as JSON.
Here's the function I'm trying to use:
function get_github_public_repos(username) {
var the_url = "http://github.com/api/v2/json/repos/show/" + username
$.ajax({
url: the_url,
dataType: 'json',
type: 'get',
success: function(data) {
alert('raw data: ' + data)
var json_response = $.parseJSON(data);
alert(json_response);
}
});
}
This is returning Null for data. And in the console, I see Failed to load resource: cancelled. I know the URL is correct, because if I run curl on the url, it returns the expected data.
jQuery's ajax function supports JSONP which allows cross-domain requests (which you need because you're trying to request data from github.com from another domain). Just change the dataType from 'json' to 'jsonp';
function get_github_public_repos(username) {
var the_url = "http://github.com/api/v2/json/repos/show/" + username
$.ajax({
url: the_url,
dataType: 'jsonp',
type: 'get',
success: function(data) {
var json_response = data;
alert(data);
}
});
}
UPDATE: It's import to note that the end pint (in this case github.com's API) has to support JSONP for this to work. It's not a guarnateed solution for ANY cross-domain request as pointed out in the comments.
JavaScript is subject to cross-domain restrictions when making requests on a different server.
Well, unless you run your code in the github.com domain, that won't work.
You can use simle ajax only in your domain.
One solution is to create a proxy for it. Make a page on your server that does one thing, gets your requested (out of domain) content with curl, and prints it. Then you call this proxy with ajax.
The XmlHttpRequest object (which $ajax uses) cannot download content from a different domain due to the same origin policy. You would need to use something such as JSONP to be able to do this from a browser.
As the others have said, you cannot execute ajax on a remote domain.
You will need to write a server sided script on your domain (such as php), that will do the dirty work retrieving the information needed from the github domain.
Then, use your ajax to query your server side script for the information.
I know the URL is correct, because if
I run curl on the url, it returns the
expected data.
Use that idea to get your ajax working. Create a proxy page on your site that uses curl to retrieve the data you want, then have your "the_url" variable point to that page on your site. Cross-domain restrictions prevent you from being able to use ajax in the manner you attempted.

Categories

Resources