I am trying to access a NetSuite restlet using jQuery. Here is my code for that:
jQuery.ajax({
url: "https://rest.na2.netsuite.com/app/site/hosting/restlet.nl?script=270&deploy=1&searchId=customsearch_active_models",
type: "GET",
dataType: "json",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "NLAuth nlauth_account=ACCOUNT#, nlauth_email=EMAIL, nlauth_signature=XXXXXX, nlauth_role=ROLE#")
}
})
.done(function(data){
console.log(data);
});
When I check the "Network" tab in Chrome/FF it's giving me the following 401 response:
XMLHttpRequest cannot load https://rest.na2.netsuite.com/app/site/hosting/restlet.nl?script=270&deploy=1&searchId=customsearch_active_models. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.tracksandtires.com' is therefore not allowed access. The response had HTTP status code 401.
Am I not formatting the Authorization part correctly? I can't find any documentation on accessing a NetSuite Restlet via jQuery so I'm sort of shooting blind here. Should I just use vanilla javascript and not jQuery? Any help would be much appreciated!
Try using jsonp like this:
jQuery.ajax({
url: "https://rest.na2.netsuite.com/app/site/hosting/restlet.nl?script=270&deploy=1&searchId=customsearch_active_models",
type: "GET",
crossDomain: true,
dataType: "jsonp",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "NLAuth nlauth_account=ACCOUNT#, nlauth_email=EMAIL, nlauth_signature=XXXXXX, nlauth_role=ROLE#")
}
})
.done(function(data){
console.log(data);
});
More info:
How does Access-Control-Allow-Origin header work?
Basically don't
Although #adolfo-garza 's answer does show JSONP correctly you gain nothing by using a Restlet and you give up a login that can never be used for something sensitive. Basically you've put one of your Netsuite credentials out on the public internet. Nothing good can come of this.
This is one of the use cases for Suitelets. You create a Suitelet that has public access (available without login; audience all roles) and then you don't need authentication (though there are ways to rely on shopping session or checkout session authentication if you need filtering information by customer).
If you are just trying to test a real Restlet Use Case then you should use Node or some non-browser based application to do that.
Related
This question already has answers here:
Unexpected token colon JSON after jQuery.ajax#get
(2 answers)
Closed 7 years ago.
I am trying to get data with Ajax.
Data is json. I use jquery and angular.
But result is undefined or error.
Here is my jquery code:
$(document).ready(function() {
var url = "http://market.dota2.net/history/json/";
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data);
}
});
});
In Angular i am usin jsonp method. Whats wrong ?
By the way, in pure Java i can get data from this url...
Whats wrong?
You're trying to call an endpoint that provides JSON as though it provided JSONP. That won't work; they are different (though related) formats.
Example JSON:
{"foo":"bar"}
Example JSONP:
callback({"foo":"bar"})
Note the difference: JSONP is actually a JavaScript function call, wrapped around the JSON.
If the API supports JSONP, call an endpoint that supports it.
If not, you can't query it directly unless the provider supports Cross-Origin Resource Sharing and shares with your origin, because of the Same Origin Policy that applies to ajax calls.
By the way, in pure Java i can get data from this url...
Because the Java code is not running in a context that is controlled by the SOP, and so can get the data from that endpoint (as JSON) and use it. This is also the same reason that just posting that URL into a browser address bar lets us see the data. But ajax calls are governed by tighter rules.
If you expect json, dont use jsonp but json.
$(document).ready(function() {
var url = "http://market.dota2.net/history/json/";
$.ajax({
type: 'GET',
url: url,
async: true, /* it fails with false */
contentType: "application/json",
dataType: 'json',/* <== here */
success: function(data) {
console.log(data);
}
});
});
Are you using jsonp consciously ? Do you know what it is ? If not, use json. Or get informed about JSonP: https://en.wikipedia.org/wiki/JSONP
I tried on Safari:works.
On Chrome & FFox: does not work + Erreur "Cross Domain Origin"
XMLHttpRequest cannot load http://market.dota2.net/history/json/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
That means you cannot get JSon with your client/machine from the API server. So you should indeed use JSonP, but... you miss the callback or something in the API documentation.
Im trying to accomplish SOAP-post to get back XML data.
Problem is that "No 'Access-Control-Allow-Origin' header" and I suppose that the server needs to add the header.
So I created a MockService in SOAPui and copied the server response. But I still get the same problem. In soapUI in the response I added this http://imgur.com/TZXM2Ca
function soap() {
var sr = MySoapRequest;
$.ajax({
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader("SOAPAction", "x");
},
type: "POST",
dataType: "xml",
data: sr,
crossDomain: true,
success: function (data) {
console.log(data);
},
error: function (error) {
},
contentType: "text/xml; charset=\"utf-8\""
});
}
By default, browsers cannot make POST requests via AJAX to URLs which are not in the same origin as the current page. For example, if you have open a page that sits in the URL http://foo.com, and that page tries to post some data (via AJAX) to http://bar.com, you will normally get the error you are seeing now.
If you want to make this work, you have to configure your server to accept requests via Cross-Origin Resource Sharing (CORS). I suggest that you get some information about CORS, you can find a lot of documentation online about it. An extensive overview can be found here.
As for the actual implementation of CORS on your server, it depends on which platform you are using. If you are using PHP, have a look at this question.
I'm using a jquery ajax call to a recurly API endpoint, but I get cross-origin errors. From my understanding, this is because Recurly only returns results as XML... when I use JSONP to get around cross-origin errors, I get an error because it receives the XML data but expects JSONP. Pretty obvious. But I'm trying to understand how exactly can one use this API at all via AJAX calls. I've been successfully able to access the API with PHP, but unfortunately, for this project, I can't use any client-side code.
Even if I find some sort of middle-code solution to get the XML and convert it to JSON for my side to accept, I need to utilize the API for POST requests (creating accounts, subscriptions, etc.) so I would like to understand how to utilize the API properly.
Here is an example of my code:
$.ajax({
url: "http://[DOMAIN].recurly.com/v2/accounts",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + window.btoa("[API KEY]"));
},
crossDomain: true,
type: "GET",
accepts: "application/xml",
dataType: "application/xml; charset=utf-8",
success: function (data) {
console.log("SUCCESS:", data);
},
error: function(e){
console.log("ERROR:", e);
}});
Anyone with Recurly API experience have any tips/advice?
From https://docs.recurly.com/api/recurlyjs/jsonp_endpoints
$.ajax({
dataType: 'jsonp',
url: 'https://{subdomain}.recurly.com/jsonp/{subdomain}/plans/{plan_code}',
data: {
currency: 'USD',
},
success: function (data) {
// do stuff
},
}
You should not use the V2 API from the browser. Doing so risks exposing your private API key. If someone has your API key they can make calls charging customers, modifying subscriptions, causing all sorts of problems.
Look at the JSONP endpoints that Byaxy linked to.
I want to read rss(xml) file but without using google rss feed.
i have try jsonp but it download the file and it throw a error "Uncaught SyntaxError: Unexpected token < "
$.ajax({
type: "GET",
url:'https://news.google.com/?output=rss',
//url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: "xml",
contentType: "text/xml; charset=utf-8",
headers: { "Access-Control-Allow-Origin":"*",},
success: function(xml) {
alert("success");
}
});
plz guys help me..
$.getJSON("//ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?", {
num: 10,
q: url
}).done(function (data) {
console.log(data);
});
Notes:
You're overdoing it. Don't try to specify information on the client side that the server actually has to supply (content type, allow origin headers, data type).
You don't want XML, you want JSON.
The name for cross-origin JSON requests is JSONP.
jQuery implements that for you if you use the getJSON() API method. You don't have to do anything besides adding "callback=?" to the URL.
Use jQuery Deferred callbacks (then, done, fail and always). They allow your code to become a lot more flexible.
Have a look at the documentation, too. https://developers.google.com/feed/v1/jsondevguide
You basically can't implement a web client RSS reader because you can't be sure that content providers will set the correct CORS header for their feed(s) ; My advice would be to not waste your time reading through endless CORS/JSONP lectures (and trying misleading code) but implement a server solution (like, say Pétrolette) and move on.
I have developed WCF rest service and deployed it on a link that can be accessed via the browser because its action is "GET".
I want to get that data using jQuery. I tried my best to get WCf get response using jQuery
but in vain. I also tried $.Ajax with 'jsonp' with no luck. Can any one help me?
The url is: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation
You can check that url response by pasting url in browser.
You need to set Access-Control-Allow-Origin to value [*] in your response header.
this blog gives the more details how it can be done in WCF REST service
if you were to do this in Web API you could have just added
Response.Headers.Add("Access-Control-Allow-Origin", "*")
calling the service using a fiddle
$(function() {
$.ajax({
url: "http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation",
datatype: 'json',
type : 'get',
success: function(data) {
debugger;
var obj = data;
}
});
});
I got the error
XMLHttpRequest cannot load
http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation.
Origin http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.
I can't make a cross domain example to show you but
$('#a').load('http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation?callback=run');
would work had those things been set.
Your service needs to either enable JSONP callbacks or set the Access-Control-Allow-Origin header for cross domain requests to work, or you need to run the script from the same domain. Given that your url says AndroidApp I'm thinking you want cross domain.
Sample code below:
$.ajax
(
{
type: 'GET',
url: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation,
cache: false,
async: true,
dataType: 'json',
success: function (response, type, xhr)
{
window.alert(response);
},
error: function (xhr)
{
window.alert('error: ' + xhr.statusText);
}
}
);