Access response data in JSONP request - ajax

I have a SAP Gateway OData-Service and a local Tomcat Apache Server. My SAPUI5 Client is deployed in the Tomcat and requests a OData-Webservice from the SAP Gateway remote server. In fact there is a cross origin domain error. So I set the header "Access-Control-Allow-Origin" in my OData-Webservice and my SAPUI5 client requests with JSONP, but I will get an error because the SAP Gateway can't handle with JSONP responses.
My code:
The error: "Uncaught SyntaxError: Unexpected token :"
The error depends on the incompatibility of the SAP Gateway to JSONP.
If I look in the network requests I will find this one:
It is the JSON (not JSONP) response from the webservice.
So my question. Is there a possibility to access to this response?
I tried to access via a lot of callbacks like success, error, fail, done, always, complete, and so on. But no chance...
thanks and best regards

$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(response) {
//this is where you'll get data/response
console.log(response) ;
},
error: function(e) {
console.log(e.message);
}
});
Update:
Problem is with your context.. there is some value like _1453458442107=:1
Check that and encode it.

If you set the CORS header "Access-Control-Allow-Origin" in the odata responses you should be able to access the service with regular JSON (without the P).
JSONP is a workaround to circumvent the same origin policy when the CORS-Headers are not available.
If your odata service uses authentification it might be necessary to set some more CORS headers to get it working.
On MDN you can read more about CORS and its headers.
On Wikipedia is a chapter about CORS vs JSONP.
So have you tried something like the following?
$.get({
url:"https://.../sap/opu/odata/sap/ZMOBILAD_SRV/UsernameSet?$format=json",
context: document.body,
cache: false
}).done(function(){
console.log(this);
});

Related

CORS could not get fixed even after adding Access-Control-Allow-Origin in service

I tried to access a Rest service which was hosted in different domain from mine through an ajax call and I got "CORS" error in the firebug.
After researching about this problem, I figured out that the service needs to be changed by adding Access-Control-Allow-Origin to * in the response header. I did that in the service as well.
public Response search(String expression) {
return Response.ok() //200
.entity(ConnectionUtils.query(expression))
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.header("Access-Control-Allow-Headers", "Content-Type,Accept")
.allow("OPTIONS").build();
}
Above method is the implementation class of below service interface:
#POST
#Path("/search")
public Response search(String expression);
I tried to post a request to this url through chrome advanced rest client, I am getting the response as well. Also the response header shows that the Access-Control-Allow-Origin has been set properly as well. Please refer to below screenshot of chrome client:
If you see above, the response headers has been changed.
But my below ajax call always return CORS error:
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.100:8080/cqs-1.0-SNAPSHOT/services/services/cqs/search. This can be fixed by moving the resource to the same domain or enabling CORS."
$.ajax({
type: 'POST',
url: "http://192.168.1.100:8080/cqs-1.0-SNAPSHOT/services/services/cqs/search",
crossDomain: true,
dataType: 'json',
data: {"offer.offer.offerId.USSellerId": {$gt: 0}},
headers: {
"Accept": "application/json",
contentType: "application/json"
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data.statusText);
console.log(data.name);
}
});
Don't use CORS. It's fraught with peril. Rather, set up a simple reverse proxy on the server using Apache (or similar). Once you set it up, all requests from your app can go back to your domain/port thus not triggering any OPTION methods from the browser. Meanwhile your reverse proxy can redirect requests based on the path in the url, which is completely up to you on how you want to configure.
In my case, I just had a simple case of needing to access 2 different ports on the same server. Port 8080 (tomcat) was serving my GWT UI and REST requests from my GWT pages (using RestyGWT) were needing to hit port 9000 (Play framework port). Due to the different ports, CORS was required to deal with the OPTION 'preflight' checks that the browser was doing.
To solve this I just setup my URLs as having either /ui path or a /api path.
Since the domain/port was the same, and my proxy could easily redirect transparently to the correct port (api -> 9000 and ui -> 8080) there was no longer any need for CORS.
CORS has a lot of issues in my experience including cookies. It's really better to avoid it using a reverse proxy.
If you need more details, I can post more - let me know.
JR

Ajax post being aborted by firefox (not seen in Chrome or IE)

When using firefox, an ajax post request i have is being reported as aborted in firebug. The ajax post works fine in IE and Chrome. It is not a cross domain request. I tried looking at the issue using fiddler, and when fiddler is capturing web traffic (with options set to decrypt https) the post works. The post issue cannot be created in my local development environment, as all Firefox attempts successfully post the data I'm sending via ajax. Any idea why the post works while fiddler is running? It might give me some idea of how to get it working.
$.ajax({
type: 'POST',
url: '/Save',
data: JSON.stringify(dataset),
datatype: "html",
contentType: "application/json",
success: function (data, textStatus, jqXHR) {
//alert("success");
},
error: function (jqXHR, textStatus, errorThrown) {
//alert("error");
}
});
Also, this ajax request is called by a number of methods, and only when the largest of the datasets is sent does it fail.
Try only
async: false
in ajax option, I had the same problem.
I would start by explicitly setting (and changing) some of the basic ajax options:
cache: false,
timeout: 60000,
async: false
What type of content your server returning. JSON or HTML content. Are you using charset=utf-8 in server content. Make sure your server response must be in JSON contentType. Another guess remove datatype: "html" from your code. Try for your luck.
If your server returns json means, try below
$.ajax({
type: 'POST',
url: '/Save',
data: JSON.stringify(dataset),
datatype: "json",
contentType: "application/json",
success: function (data, textStatus, jqXHR) {
//alert("success");
},
error: function (jqXHR, textStatus, errorThrown) {
//alert("error");
}
});
datatype: "json", contentType: "application/json" makes sense
If you send this AJAX request from an event handler (example : click of a submit button), be sure to prevent the browser's default behavior (submitting the form), until you'll have 2 HTTP requests fired, with the first being aborted.
You can use e.preventDefault() to achieve this.
I just had this trouble on IE8.
Check the maximum post size setting on your server.
I also had similar issues and tried some of the ideas described above.
I finally fixed "aborted" state by :
adding e.preventDefault(); and return false; to buttons event handlers
adding datatype: "json", contentType: "application/json", to jQuery.ajax method params.
Thx to everyone for the clues.
This is either a cross domain issue or it is an issue with Firefox aborting your request because request is async. For cross domain you can check the origin of your request and what is allowed on webservice. You might have to read up on CORS.
If it is not cross domain then it is certainly a problem with request being async. Just change it to sync.
If you are using 2-way SSL auth on a CORS request, Firefox will abort your jQuery ajax requests by default. This is due to differing implementations of CORS in Firefox and Chrome. You can resolve this issue in your client code by adding withCredentials: true to your XHR instances. In jQuery, you can add this to the ajax call:
xhrFields: {
withCredentials: true
}
Check out these bug reports for more details:
Chrome sends TLS client certificates in CORS preflight, in violation of spec requirements
TLS handshake fails on CORS requests because no certificate is sent
I've also noticed that Firefox still absolutely refuses to send credentials on OPTIONS preflight requests, so you will need to configure your server to not require them (which seems crazy to me in a 2-way SSL scenario).

How do I make a Cross-Domain Request in Firefox?

I am using the following jQuery AJAX call to access a SOAP Web Service:
jQuery.ajax({
url: url,
type: "GET",
dataType: "jsonp text",
crossDomain :true,
data:"i="+'a'+"&j="+'b',
processData: false,
success: OnSuccess,
error: OnError
});
This code works fine in IE but it get an empty response in Firefox. On further searching it seems Firefox does not allow cross domain requests by default, or it processes the header information differently.
My application is on localhost:8081, and the WebService I want to consume is on localhost:8080. Is there any way I can allow Firefox to make a cross domain request?
See https://developer.mozilla.org/en-US/docs/HTTP_access_control
ya, This issue is resolved after I installed CORS add-on for firefox. But is there any other way, I can set the parameters using JQuery-ajax code?
you need send "Access-Control-####" headers same what in OPTIONS request response.

Why does my web service call fail when calling a different site

I am making a JQuery ajax call to a web service like so:
$.ajax({
type: "POST",
url: "https://WebsiteName.com/Service.asmx/LoginExternal",
data: "{loginData: " + JSON.stringify(LoginData) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
... Stuff ...
},
error: {
... Error Alert ...
}
});
When I am on the actual web site, this succeeds. When I am on localhost and use a relative path, it succeeds. However, when I am trying to access the web site (using an absolute path) from localhost, I get the error message that the call failed.
This would seem to indicate that it is a permissions problem and I've made sure that the web.config doesn't require authentication for access to the web service but I'm not sure what else to check. Any help would be greatly appreciated!
Update: The "thrownError" that I am getting is "No Transport" - hopefully that helps.
Security:
http://en.wikipedia.org/wiki/Same_origin_policy
Being an unsecured scripting logic, ajax requests made using JavaScript (or JQuery) are stucked on same host, protocol and port, due to unauthenticated and unencrypted requests.
A method for passing requests to a different host, you must implement a bridge service written in a secure language (ex. Java), deployed on same host that passes your requests further to your services, and then passes response to your ajax call.
Your ajax call will be on the bridge service then.

Access-Control-Allow-Origin Error Trying to GET json

I'm trying to utilize the Bing API to pull back spelling suggestions, but keep getting the below error:
XMLHttpRequest cannot load http://api.search.live.net/json.aspx?Appid=myIdWasHere&query=explotion&sources=spell. Origin http://myWebServerNameWasHere is not allowed by Access-Control-Allow-Origin
I read a couple posts that looked similar, then about CORS, but I'm still a bit fuzzy. What do I have wrong in the below code?
$.ajax({
type: 'GET',
url: 'http://api.search.live.net/json.aspx',
dataType: 'json',
data: {
Appid: '<myIdWasHere>',
query: 'explotion',
sources: 'spell'
},
beforeSend: function(xhr){
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
success: function(data) {
alert(data);
},
error: function(msg) {
alert(this.url + " -Failed"));
}
});
CORS (http://www.w3.org/TR/cors/) is a newish way of making cross-domain requests using XmlHttpRequest. Since you are making a request from your domain to api.search.live.net, it is considered a cross-domain request. CORS requires server-side support in order to work; specifically, Bing needs to include a special header that indicates that cross-domain requests are allowed.
My guess is that the Bing API does not allow cross-domain requests. In order to make a request, you should instead look into using JSON-P (http://en.wikipedia.org/wiki/JSON#JSONP). From their documentation, it looks like Bing does support JSON-P. Check out the "Callback Enumeration Example" section here:
http://msdn.microsoft.com/en-us/library/dd250846.aspx
Old post, but the Access-Control-Allow-Origin should be on the server not the client/calling domain.

Resources