Not cross-domain. XMLHttpRequest cannot load localhost:portNo1 . Origin localhost:portNo2 is not allowed by Access-Control-Allow-Origin - javascript

I have a server created from BaseHTTPServer.HTTPServer in Python at localhost:portNo1
Client-side is at localhost:portNo2 and at client-side, I am making a jQuery $.ajax POST request like this:
var request = $.ajax({
url: "http://localhost:portNo1",
type: "post",
dataType: 'json',
data: json_data
});
At server side, server gets the data from client and replies with its data.
def do_POST(self):
# Get client data
length = int(self.headers.getheader('content-length'))
data_string = self.rfile.read(length)
print data_string;
# Create response object
jsonObjStr = json.dumps(jsonObj);
self.send_response(200)
self.end_headers()
self.wfile.write(jsonObjStr);
What happens is that server is getting the data I sent, but there is no reply to the client and the callback at the fail event of $.ajax object executes at the client-side(error msg). I debugged and verified there is nothing with jsonObj. But I cannot see what is inside self.wfile object.
At the JS console, I get the following error also (it shows up at the JS console of Google Chrome and it doesn't show up in Firefox JS console):
XMLHttpRequest cannot load localhost:portNo1 . Origin localhost:portNo2 is not allowed by Access-Control-Allow-Origin. client.html:1
The JS console at Google Chrome points to html file, but that didn't make sense for me, either.
I checked the website and it seems that the error is generally caused due to cross-domain requests. However, I am communicating from one localhost port to another.

Well, that's the problem. Cross-origin restrictions do not allow you to communicate across ports without sending a Access-Control-Allow-Origin: * header.
A better solution would be to use Nginx or some other webserver to reverse proxy those two running applications to the same domain and port.

Related

Call ajax HTTP to API with Sinatra

I'm calling a service from my api built with sinatra, and I make a simple ajax call as I mention it below:
<script>
$(document).ready(function (){
seeStatus()
});
function seeStatus(){
token = $('#token').val();
$.ajax({
url: '/see/v1/status/' + token,
type: 'GET',
dataType: "script",
complete: function (response) {
var json = $.parseJSON(response.responseText);
if (json.error == 0) {
window.location.href = json.href
}
}
});
}
</script>
made a GET call and the server receives a call OPTIONS
190.141.191.102 - - [08/Mar/2018:12:31:38 +0000] "OPTIONS /see/v1/status/f4dce2eb193674cab37ff36cbaca2eb4c0355165?_=1520512306539 HTTP/1.1" 404 51 0.0133
The code of my service is not executed from the ajax method and I do not understand why? , when I try my service independently with an HTTP client it works correctly What can I do? Any help Thanks
It looks like you're having an issue with CORS (Cross-Origin Resource Sharing). It would be interesting to know where the script requesting the API and where the API itself are located. I guess they're not on the same server.
In a nutshell, CORS is a mechanism that prevents a resource on one domain to freely access a resource on another domain. Your webpage can load resource on its own domain (scripts, stylesheets, fonts, json, etc.) but by default, Javascript HTTP requests (XMLHttpRequest / fetch) use the same-origin policy by default, which means they can only request resources on the same domain.
According to the CORS dedicated page on the MDN, here's the reason for the OPTIONS request you see on the server side:
the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method"
I guess you'll have to configure CORS on your server, or make it so that the HTML file calling the API is located on the same domain as the API itself (which might not be possible).
Since you used the Sinatra tag in this question, I guess your server is written in Sinatra, in that case you can use the britg/sinatra-cross_origin gem to setup CORS rule on your API server.

REST request from app works, but not from javascript

I'm building an app that has to get and set data at a remote web service through requests. When I use the jQuery GET request it works fine, I can request data from the service without any problems, but when I use PUT I get some erros:
OPTIONS http://myurl.com 501 (Unsupported method
('OPTIONS'))
OPTIONS http://myurl.com Origin null is not allowed by Access-Control-Allow-Origin.
I've tried almost anything to get this to work, but it won't work. I've download a chrome app called REST Console, which can make custom REST requests. The strange thing is that I can interact with my server over that app but not through my javascript!
This is the javascript:
$.ajax({
url: 'http://myurl.com',
type: 'PUT',
data: '<time>16:00</time>',
success: function(data) { alert(data); }
});
Could anybody tell me what is going on here?
First ensure you're serving the page that runs the script from a web server, not directly from the file system.
I'm guessing your service at http://myurl.com is at a different host name to the host name your page is being served from? For it to work in this case you need to implement HTTP headers to support Cross Origin Resource Sharing.
Your service at http://myurl.com needs to handle an HTTP OPTIONS request, the response to which should be a set of HTTP headers (with no content) as follows:
Access-Control-Allow-Origin: http://url-of-page-with-javascript/
Optionally you can also specify Access-Control-Allow-Credentials, Access-Control-Allow-Headers and Access-Control-Allow-Methods. See the full specification here.
You'll also need to add the same headers with the same values when your server responds to the PUT request - obviously the content will also be included with this response.

Connect to webService using AJAX and CORS

I'm developing a phonegap App with html5, css, js and jQuery Mobile and I need to connect to a webservice which is already done and fully working. The problem is the Access Control Allow Origin and the Cross Domain. As if it wasn't hard enough I have to think about the authentication too, essential to connect to the web service. I already done my research, read a lot of tuts, tried a lot of solutions, some of them using jsonP which looked to me the closest one to work. The thing is I'm new at this and no tutorial looked good, so hopefully someone here could lead me the way. The webService was build in asp.net and I have full access to it if it's needed. I'm using AJAX to make the "call" but I can't pass the ForeFront authentication .
Here's the JS+AJAX code:
function conteudoProg() {
var webMethod = "myURL";
var credentials = {
username : "myUser",
password : "myPass"
};
$.ajax({
type : "GET",
url : webMethod,
//data: credentials,
contentType : "application/json; charset=utf-8",
dataType : "jsonp",
success : function(msg) {
alert(msg);
},
error : function(e) {
alert(e.status + " " + e.statusText );
}
});
}
If I change my dataType from jsonp to json, I get this error:
OPTIONS https://myURL 440 (Login Timeout)
XMLHttpRequest cannot load https://myURL Origin http://127.0.0.1:8020 is not allowed by Access-Control-Allow-Origin.
With jsonp, the error looks like this:
Resource interpreted as Script but transferred with MIME type text/html: "https://myURL/CookieAuth.dll?GetLogon?curl=Z2FWSInqueritosZ2FServā€¦1820135927463_1359737732559Z26_Z3D1359737732605&reason=0&formdir=3". jquery-1.8.2.min.js:2
Uncaught SyntaxError: Unexpected token <
Requests to another domain will cause a pre-flight OPTIONS request to see whether the requesting domain can make calls to this domain.
The receiving end needs to emit the correct headers or your browser will block the request and give you the error you posted.
Say you are requesting from mydomain.com to webservice.com
Then webservice.com/api should emit these headers:
Access-Control-Allow-Origin: http[s]://mydomain.com
Access-Control-Allow-Credentials: true # if you want cookies
Access-Control-Allow-Headers: Content-Type, X-Custom-Header # any extra headers you want to send
Make sure the webservice knows about OPTIONS requests. It really only needs to emit some CORS headers, it doesn't need to do anything else (like process a request to it's API).
You don't need to change anything in your AJAX handler, it will pass as any other request. If you want cookies make sure to set http_request.withCredentials = true;
Keep in mind that an HTTPS URL is considered to be different from an HTTP domain and make sure your HTTPS certificate is valid, if it's not valid the request may fail silently. If you're using a self-signed certificate (for testing) add it to your browser or OS whitelist.
Cross domain request from HTTP to HTTPS aborts immediately
As for compatibility. Earlier versions of Internet Explorer (8 and lower) use ActiveXObject, this API is very bad at CORS. It doesn't support authentication/cookies or custom headers (such as Content-Type: application/JSON). I would recommend a JSONp fallback.
The code does not work because when you tell jQuery that the .ajax method expects a dataType json, that's what's trying to parse the response into. If the response is html then you should use a dataType html (or none, to let the default intelligent guess do it's work). See jQuery.ajax() dataType for more info.

Ajax request works in remote server but not in local server (with Codeigniter)

I've a web application wich makes Ajax requests to a server with Codeigniter-php code. The Ajax requests work correctly in local server but not when the application is hosted in remote server.
The console errors are:
XMLHttpRequest cannot load http://localhost/CI-example/index.php/control/controlHome. Origin http://www.page.com is not allowed by Access-Control-Allow-Origin.
Surprisingly, the request is made in the server but not the response.
The URL that I use to Ajax request is:
AJAX_URL = "http://localhost/CI-example/site/index.php/control/controlHome";
But, also I've tried with:
AJAX_URL = "http://www.page.com/CI-example/site/index.php/control/controlHome";
And the next error is captured:
POST http://www.page.com/webdom/site/index.php/control/controlHome 500 (Internal Server Error)
How can I do?
Edit:
www.page.com is a subdomain. Is necessary to do some configuration when a subdomain is used to Ajax request?
And the folders organization is:
/CI-example
---/application/controllers/control.php
---/system
---/site/js/ajaxRequest.js
As I am getting here, while you are sending ajax requests to the server than it's returning 500 (Internal Server Error). I'm sure that the error is from server side, and there may be following reason-
If everything is fine in the codes, then may be your base_url is different from what you are requesting. Yes this can cause the problem, for example if you have hosted your web application and your base_url is www.mysite.com and you are requesting for mysite.com.
Next reason may be, that you have developed your project in windows or any system which is in-case-sensitive but when you will upload to any linux like server than each and every file name will be case-sensitive. For example suppose a model file name you have given is MyModel.php but when you will load the model, it will generate the error like Unable to find the specific class.
You cannot make HTTP POST requests using AJAX to a different domain, unless that page allows you to do so using a special header called "Access-Control-Allow-Origin".
localhost is different to page.com which is why this will not work.
Response on the http://www.page.com's url say something has gone wrong during the page execution. Your PHP error log should help you to find what.
Adding the line ini_set('display_errors', 1) might return the error to the ajax request, in the error handler. Don't forget to remove the line after use, you don't want this lying around in production code.
The second error is : 500 (Internal Server Error)
This means there was an error on the server side - not a cross-origin policy problem.
This is probably an error in the execution of your PHP script.
Check your error log (e.g : if you use the standard LAMP stack, the error log should be somewhere in /var/log/apache2/)
try this,
http://localhost/CI-example/index.php/control/controlHome
instead of
http://localhost/CI-example/site/index.php/control/controlHome
in your ajax URL.
As from your folder structure, there is no need to include "site" in your URL

tcp handshake terminated by FIN /JSON data not retrieved

Hi
I have a website html embadded with java script, the website uploaded into apache tomcat, the website suppose to contact another server and retrieve json data back, this is not happening the packet tracing shows the tcp handshake is terminated by a FIN state the packet send before the FIN state has a checksum incorrect, I'm not sure how to troubleshoot this ? do you think the checksum incorrect is terminating the handshake ? and hwo to avoide that ? the following is my ajax jquery code
note: both apache server and the other server are in the same domain.
Thank in advance
LS
$(document).ready( function() {
var home_add='http://myhome.net:3300/gateway';
$('#handshake').click(function(){
alert(" sending json data");
$.ajax({ /* start ajax function to send data */
url:home_add,
type:'POST',
datatype:'json',
contanttype:'text/json',
async: false,
error:function(){ alert("handshake didn't go through")}, /* call disconnect function */
data:{
"supportedConnectionTypes": "long-polling",
"channel": "/meta/handshake",
"version": "1:0"
},
success:function(data){
$("p").append(data+"<br/>");
alert("sucessful handshake")
}
})
})
})
You seem to be misunderstanding the same-origin policy. The same-origin policy used by XMLHttpRequest, the basis for jQuery's AJAX functionality, is:
The two hostnames must be exactly the same (not just part of a higher level domain).Example: A web page from careers.stackoverflow.com can access the same domain but not beta.careers.stackoverflow.com, stackoverflow.com, or foo.stackoverflow.com.
The two protocols must be exactly the same (http/https).Example: A web page from http://stackoverflow.com cannot access https://stackoverflow.com and vice-versa.
The two port numbers must be exactly the same (except in Internet Explorer).Example: A web page from http://stackoverflow.com cannot access http://stackoverflow.com:8080 and vice-versa in Firefox, Chrome, Safari, or Opera.
You will have to do one of these:
Use the Access-Control-Allow-Origin HTTP header in AJAX responses, with the obvious disadvantage of excluding browsers such as IE and older versions of the others that do not support it
Use JSONP, which is supported by jQuery though not for synchronous requests (which you should avoid anyway because they can hang the browser)
Proxy HTTP requests from the server your web page is served on to the other server

Categories

Resources