xhr sending requests to specific port? - ajax

I am very new to ajax development, I am trying to use xhr to get and post data,the problem is when I use port based requests?
here is my working code and not working codes
$.ajax({
url : "login.php",
type : "post",
data : {
userProfile : JSON.stringify(data)
},
success : handleDBResponse,
error : function(jqXHR, textStatus,errorThrown) {
console.log("The following error occured: "+ textStatus,errorThrown);
},
complete : function() {
// console.log("user authentication
// successful.")
}
});
this works good, but when I am using native xhr with url:port getting no response.
function reqListener () {
console.log(this.responseText);
};
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "http://www.domain.com:443/akorp.css", true);
oReq.send();
It's not working, I was debugged and I found request status is cancelled.
.htaccess file included
Access-Control-Allow-Origin:*
still I am getting the error
www.domain.com:443 not allowed by www.domain.com Access-Control-Allow-Origin etc..
what are the possible causes for this error and how to properly send request to port?

443 is the HTTPS port. Perhaps you should try an HTTPS URL instead of forcing the port.
I'm not sure I want to know why you're pulling a CSS file from somebody else's serer with xhr.

Related

HTTPS Ajax request failure when SSL Certificate changed

In our system we have a case, when SSL certificate changed in backend, and as you can imagine Ajax requests are not working after that.
Ext.Ajax.request({
url : 'myaction',
method : 'POST',
success : function(response, options) {
// some code here
},
failure : function(response, options) {
// when SSL changed request failed
}
});
In response we have no additional data to understand if the problem is because of SSL change.
What I want to do?
If there will is any option to understand if failure because of SSL changing I will be able to show some message and then just reload the page to allow user accept new one.

Access denied in IE 10 and 11 when ajax target is localhost

I'm trying to do a ajax call between a server (http) that is on internet. And target that to my own localhost. FF/Chrome/ ETC... works. It's ONLY an IE issue. IM USING IE 11 AND 10.
The request is don't even done. The "denied access" is thrown instantly.
This is the code. Just for you to see.
Is not the classical HTTP/HTTPS error in IE8 AND IE9. This is something else, but the documentation is not helpful.
$jq.ajax({
contentType: 'application/json',
url: url,
dataType: 'json',
crossDomain: true,
beforeSend: function (xhr) {
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", "Basic " + $jq.base64.encode(username and password));
},
success: function (data, status, headers) {},
error: function (xhr, status, error) {}
The status is 0 in xhr object and error is "Denied access"
Internet Explorer raises this error as part of its security zones feature. Using default security settings, an "Access is Denied" error is raised when attempting to access a resource in the "Local intranet" zone from an origin in the "Internet" zone.
If you were writing your Ajax code manually, Internet Explorer would raise an error when you try to open the resource. For example:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost/', true); // This line will trigger an error
xhr.send();
You can work around this error by adding the origin site to the "Trusted sites" security zone. You can test this by adding "http://client.cors-api.appspot.com" to your "Trusted sites" zone and using this test page at test-cors.org with your localhost site as the Remote URL.
In addition to the trusted site requirement I found that the problem was not fixed until I used the same protocol for the request as my origin, e.g. my test site was hosted on a https but failed with any destination using http (without the s).
This only applies to IE, Chrome just politely logs a warning in the debug console and doesn't fail.
If you are attempting to make cross-origin ajax requests in IE9, you'll need to use XDomainRequest instead of XMLHttpRequest. There is a jQuery plug-in that wraps XDR. You should be aware that there are some notable limitations of XDR.
Another option would be to use a library like this: https://github.com/jpillora/xdomain.
jQuery implements ajax calls using the XMLHttpRequest object which is not supported in IE9. You have to force it to use XDomainRequest instead.
I get around this problem using this jQuery plugin:
https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
Note:
Do not use "http://www.domain.xxx" or "http://localhost/" or "IP" for URL in Ajax.
Only use path(directory) and page name without address.
false state:
var AJAXobj = createAjax();
AJAXobj.onreadystatechange = handlesAJAXcheck;
AJAXobj.open('POST', 'http://www.example.com/dir/getSecurityCode.php', true);
AJAXobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
AJAXobj.send(pack);
true state:
var AJAXobj = createAjax();
AJAXobj.onreadystatechange = handlesAJAXcheck;
AJAXobj.open('POST', 'dir/getSecurityCode.php', true); // <<--- note
AJAXobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
AJAXobj.send(pack);
function createAjax()
{
var ajaxHttp = null;
try
{
if(typeof ActiveXObject == 'function')
ajaxHttp = new ActiveXObject("Microsoft.XMLHTTP");
else
if(window.XMLHttpRequest)
ajaxHttp = new XMLHttpRequest();
}
catch(e)
{
alert(e.message);
return null;
}
//-------------
return ajaxHttp;
};

AJAX 504 when calling ASP.NET Web API

My AJAX call is returning a 504 error when calling an ASP.NET Web API action.
More info:
Here's my API action:
public HttpResponseMessage Get(string fileName, int feedID)
{
try
{
// create file...
return new HttpResponseMessage { Content = new StringContent("Complete."), StatusCode = HttpStatusCode.OK };
}
catch (Exception ex)
{
Log.WriteError(ex);
throw new HttpResponseException(new HttpResponseMessage
{
StatusCode = HttpStatusCode.InternalServerError,
Content = new StringContent("An error has occurred.")
});
}
}
Here's my AJAX call:
$.ajax({
url: url,
type: 'GET',
success: function () {
$("#lblProgressDownload").hide();
window.open("Previews/" + fileName);
},
error: function (xhr, status, error) {
$("#lblProgressDownload").hide();
alert("Error downloading feed preview: " + error);
}
});
I get a 504 error (viewed in fiddler/ chrome console) when the file takes too long to create. The "error" parameter in the error callback doesn't return anything.
I only get the 504 error when it's hosted - on my dev it works fine.
How do I prevent this 504 error?
Note, I already tried changing the executionTimeout property in my web.config, as well as the ajax timeout. Neither worked.
HTTP error 504 is a gateway timeout:
The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI [...] in attempting to complete the request.
I suspect that means there is a proxy or gateway somewhere between you and the production server, but not your dev server, which is why it fails on the one but not the other.
Your choice is either to make your server code fast enough that it doesn't trigger the timeout, or get whoever is running the proxy server to relax their timeout restrictions (assuming it's something that you or your company controls).

Securing (ssl) a nodejs/express web service and calling it cross-domain with $.ajax()

I've set up a nodejs app like this:
var express = require('./../../../Library/node_modules/express');
var https = require('https');
var app = express();
httpsOptions = {
key: fs.readFileSync('privatekey.pem'),
cert: fs.readFileSync('certificate.pem') // SELF-SIGNED CERTIFICATE
}
var server = https.createServer(httpsOptions);
app.get('/myservice', function(req, res) {
...
}
server.listen(8443);
I have opened the 8443 port in my server for inbound requests.
From a browser, if I open https://mydomain/myservice:8443 I get the untrusted connection warning from the browser, which seems logical.
Then from a test.html that I run from my local computer (to test the cross-domain issue), I do something like this:
function testService(){
var data = { some JSON };
$.ajax({
url: 'https://myserver:8443/myservice',
dataType: "jsonp",
data: data,
jsonpCallback: "_mycallback",
cache: false,
timeout: 5000,
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error: ' + textStatus + " " + errorThrown);
}
});
}
My problem is that this request times out, and I don't think it even reaches the service.
Any idea why?
Whenever I make this request reach the server, hopefully thanks to your kind responses, what will happen with the browser warning for the untrusted certificate? Will that stop $.ajax() from silently calling the server and receiving the response?
The reason that your clients' JSONP request times out could be practically anything. Because of the way JSONP works, you can only ever know whether the request fails or succeeds, and when it fails it will always be because of a timeout. That said, its pretty much guaranteed to fail if you haven't saved the servers self-signed cert on the client. To do so, make sure that you tell your browser to always trust the servers' certificate. In Firefox you can also go Preferences->Encryption->View Certificates->Your Certificates->Import... to add the certificate to Firefox. Other browsers should have a similar interface.
To solve a potential cross domain issue, try adding the following to your app.get('/myservice'):
res.header("Access-Control-Allow-Origin:", "*");
res.header("Access-Control-Allow-Methods:", "GET");
Additionally, different browsers handle these things differently. In my experience Firefox is sometimes more lenient than Chrome, but I would definitely test in both.
To test the HTTPS issue, first I would try just setting up a regular expressjs server (no encryption) and not using https:// in your request. If the request then succeeds you know that the problem is the SSL. If so, make sure that when your browser gives a security warning you enable any options allowing you to permanently add that site to your trusted hosts.
Also, I believe that this line:
var server = https.createServer(httpsOptions);
should be:
var server = https.createServer(httpsOptions, app);
(From: http://expressjs.com/api.html#app.listen)
You may also want to add the following code below var server = https.createServer(httpsOptions); for debugging (so that you can easily see if your server receives the request):
app.get('*', function(req, res, next) {
// You *should* also be able to add the response headers here, although I haven't tried.
console.log('Request received', req, res);
next();
})
Hopefully that helps!

ajax from Chrome-Extension processed, but receive responseText="" and status=0

I am writing a google-chrome extension, that needs to make ajax requests to a server, send some data, and receive some data back. My server is Tomcat 6.0, running on localhost.
I am able to receive all the data on the server side, do all the processing I need, and send a response back to the extension,
but the status i get in the callback is 0, and responseText="".
my guess is that the problem lies either in the server - returning a response to a request originating from chrome-extension://... url, or in the extension - receiving a response from localhost:8080.
I've set the necessary permissions of course, and I tried setting content-type of the response to "text/xml", "text/html" and "text/plain" - it makes no difference.
I've tried using ajax both with XMLHttpRequest and JQuery - same problem with both.
I've found these issues, but they don't seem to solve my problem:
1. http://www.plee.me/blog/2009/08/ajax-with-chrome-empty-responsetext/
2. http://bugs.jquery.com/ticket/7653
here's my code:
bg.js (background page)
function saveText(data) {
var requrl = serverUrl + addTextUrl;
var params = json2urlParams(data);
jQuery.ajax({
type : "POST",
url : requrl,
data : params,
success : function (data, textStatus, XMLHttpRequest) {
console.log("Data Saved: " + msg);
}
});
// var xhr = new XMLHttpRequest();
// xhr.open("POST", requrl, true);
// xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// xhr.onreadystatechange = function (progress) {
// if (xhr.readyState == 4) {
// console.log("Data Saved: " + this.response);
// }
// };
// xhr.send(params);
}
addContentServlet.java: (server side)
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ErrorCodes error = addContent(request, response);
response.setContentType("text/plain");
//response.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
//response.setIntHeader("errorCode", error.ordinal());
response.getWriter().write(error.toString());
response.setIntHeader("errorcode", error.ordinal());
if(error == ErrorCodes.SUCCESS){
response.setStatus(error.toHttpErrorCode());
response.flushBuffer();
}
else{
response.sendError(error.toHttpErrorCode(), error.toString());
}
}
EDIT:
I've noticed in the chrome console of the background page that for every ajax that returns to the extension i get a
XMLHttpRequest cannot load
http:// localhost:8080/stp_poc/MyServlet.
Origin
chrome-extension://fmmolofppekcdickmdcjflhkbmpdomba
is not allowed by
Access-Control-Allow-Origin.
I tried loosing bg.js and puting all the code in the main page instead - to no avail.
how come XMLHttpRequest agrees to send the request, but not receive it back??
Maybe a server-configuration problem? I'm a newb, so maybe i missed something basic, like a header in the response
EDIT
I've finally pinned the problem:
I shouldn't have included the port number in my permission. Here's the wrong permission I wrote:
"permissions" : [
"http://localhost:8080/"
]
And here's the correct form:
"permissions" : [
"http://localhost/"
]
everything seems to works fine now.
The problem was that I shouldn't have included the port number in my permission.
Here's the wrong permission I wrote:
"permissions" : [
"http://localhost:8080/"
]
And here's the correct form:
"permissions" : [
"http://localhost/"
]

Resources