LastFM API login - CORS Issue - javascript

I am trying to use the lastFM API. I have started with a very basic template where all i wanted to do was connect to the LastFM API and authenticate myself. I have a button on my HTML page -
<button id="auth">AUTHENTICATE</button>
Here's the jQuery function to handle the click event -
$(document).ready(function() {
$("#auth").click(function() {
console.log("authenticate called");
var myUrl = "http://www.last.fm/api/auth/?api_key=32*************8a*****2";
/*$.get(url,function(data) {
alert("data");
});*/
$.ajax({
// The 'type' property sets the HTTP method.
// A value of 'PUT' or 'DELETE' will trigger a preflight request.
type: 'GET',
// The URL to make the request to.
url: myUrl,
xhrFields: {
withCredentials: false
},
crossdomain : true,
headers: {
// Set any custom headers here.
},
success: function(data) {
// Here's where you handle a successful response.
},
error: function(data) {
console.log(data);
});
});
});
I am running this on my localhost. As you can see from the AJAX request, it supports CORS. I can also see CORS header attributes being added to my request headers. But the server needs to respond with the CORS headers too like Access-Control-Allow-Origin. But the response does not contain any such headers.
But lastFM API supports CORS, so shouldn't it be sending these attributes in the response headers? Also, now how can I make use of CORS to authenticate my application?
P.S - I know I can use JSONP, but I want to know if there is any way I can handle this using CORS?

Thanks to #potatopeelings, I got the answer. What we need was not to call the authentication url, but to redirect it to a seperate page which will ask me to authorize the application to use the lastFM account. I also provided a callback URL which will redirect to my application after I have given the authorization.
So my final URL is like -
myURL = "http://www.last.fm/api/auth/?api_key=XXX&cb=http://localhost:63342"
And I removed my AJAX call to do the following -
window.location.replace(myUrl);

Related

POST data to a Google form with AJAX

I am trying to post data to a from AJAX to a Google form, but even though it reports success with a statusCode of 0, the data never appears in the form:
var dat={ "entry.529474552" :"data1", "entry.1066559787": "name1"};
postToGoogle("1FAIpQLSf4w1OQGsIncaiqXlmfAl4jYSt-e4Zx3xVJa7Weob4LnQbRZQ",dat);
function postToGoogle(id, dat) {
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', 'chrome-extension://EXTENSION_ID');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, PUT');
},
url: "https://docs.google.com/forms/d/e/"+id+"/formResponse",
data: dat,
type: "POST",
dataType: "xml",
xhrFields: { withCredentials: true },
statusCode: {
0: function() { console.log("OK") },
200: function() { console.log("error") },
}
});
}
It generates a CORS error, but supposedly, the POST should go through anyway.
For those looking to do this as of April 2019
I was working on this today. The current answer is as follows:
Each field in the Google Form has a unique ID. In order to retrieve it, get a pre-filled link by filling out all relevant form fields you wish to programatically submit
Note: In order to ensure the URL is accessible without restriction, you'll also want to disable restriction to your domain only (for GSuite paying users)
Then, copy the link and paste in your browser. The URL has a base format as follows:
https://docs.google.com/forms/d/e/[FORMID]/formResponse
Each param is a key/value pair of type: entry.XXXXXX=value
The prefilled link will give you the value of XXXXX for each relevant field
Request must be made with following headers:
Method: GET
Content-Type: application/x-www-form-urlencoded
The final request looks like this
https://docs.google.com/forms/d/e/123332233bsj333/formResponse?entry.123456=value1&entry.2333442=value2&submit=Submit
Don't forget to append submit=Submit at the end of your request!
It generates a CORS error, but supposedly, the POST should go through anyway.
While it is possible to make a successful POST request, get a CORS error, and be unable to read the response, this is only true for Simple Requests.
Because your request has:
Custom headers (Access-Control-Allow-Origin and Access-Control-Allow-Methods, which are response headers and have no business being on a request in the first place)
Credentials (i.e. you have set withCredentials: true)
… it is a Preflighted Request.
Before the browser will make the POST request, it will make an OPTIONS request to ask permission.
Since it doesn't get permission, the request fails.
Note that even if you did turn it into a simple request and make the POST successfully, you would still get a status of 0. You can't read the status when there is a CORS error.

jQuery AJAX call sending as OPTIONS and missing Authorization header

I'm starting to get stumped on this. I'm developing a C#.NET Web API service and frontend application to use it. I've been having a lot of difficulty using a token to authenticate my requests and jQuery seems to be having trouble. I can get a token just fine, but jQuery won't add it to an Authorization header in further requests.
My setup is an index.html page with several jQuery Mobile pages inside it. It starts on a '#login' page, which sends a request to my /Token URI with a username, password, and grant type. This is successful and the return is the token. The page changes to '#home' and a test ajax call is sent to /api/values to grab value. The problem is that instead of adding a header called 'Authorization', jQuery adds an 'Access-Control-Request-Headers' with the value 'accept, authorization' instead. At first I thought it was a CORS issue, but the request works fine when I use Advanced Rest Client in Chrome to send the request.
AJAX Call from '#Home'
$.ajax({
url: 'http://slalomtest2.azurewebsites.net/api/values/',
type: 'GET',
async: true,
dataType:"json",
beforeSend: function(request){
request.withCredentials = true;
request.setRequestHeader("Authorization", "Basic " + Token);
},
success: function(result){
console.log(result);
},
error: function(request, error){
$.mobile.changePage("#login");
}
});
The bad request the AJAX sends
This is what it looks like from Advanced Rest Client in the same browser
Thanks in advance for the help, I've been banging my head against the wall all day.

Salesforce OAuth with REST API using Javascript

I have an app in my salesforce developer account that I want to allow my users to access from a remote app that I am building. I see that I must use OAuth2.0 to first authorize my users before they are allowed to access the salesforce data. At the moment I am trying to use the username-password OAuth flow described on salesforce.
Step 1) I request access token using username and password via the below code snippet
var password = 'userPassword' + 'securityToken'
$.ajax({
type: 'GET',
url: 'https://login.salesforce.com/services/oauth2/token',
contentType: 'application/json',
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader('grant_type','password'),
xhr.setRequestHeader('client_id', '<client_id_here>'),
xhr.setRequestHeader('client_secret', '<client_secret_here'),
xhr.setRequestHeader('username', 'username#location.com'),
xhr.setRequestHeader('password', "password")
},
success: function(response) {
console.log('Successfully retrieved ' + response);
//Other logic here
},
error: function(response) {
console.log('Failed ' + response.status + ' ' + response.statusText);
//Other logic here
}
});
My request, however, is failing with the following message:
1) OPTIONS https://login.salesforce.com/services/oauth2/token 400 (Bad Request)
2) XMLHttpRequest cannot load https://login.salesforce.com/services/oauth2/token. No
'Access- Control-Allow-Origin' header is present on the requested resource.
Origin http://localhost is therefore not allowed access.
I have seen some sources (here here here) mention that CORS is not supported in salesforce, and that another solution should be used. Some solutions I have seen are Salesforce APEX code, AJAX toolkit, or ForceTK.
In summary, I am looking to see if (1) there is a simple mistake that I am making with my above request to get the OAuth access_token (2) or if I need to do something different to get the access (3) is there a better way to login users and access their salesforce data from my connected app?
All and any help is appreciated!
You will need to handle the OAUTH part on your own server. This isn't just due to lack of CORS, there is also no way to securely OAUTH purely on the client-side. The server could really be anything but here is an example server written in Java using Play Framework which has a JavaScript / AngularJS client as well: http://typesafe.com/activator/template/reactive-salesforce-rest-javascript-seed
You can not make this request from JavaScript. You'll need to make a server side request. There are many implementations of this flow in PHP, C#, Java, etc.
I'm posting my ajax code here that has worked for me and this CORS error in console doesn't matter. If you see in network you will get the access token.
see the ajax code below.
function gettoken()
{
var param = {
grant_type: "password",
client_id : "id here",
client_secret : "seceret here ",
username:"username",
password:"password with full key provided by sf"};
$.ajax({
url: 'https://test.salesforce.com/services/oauth2/token',
type: 'POST',
data: param,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
success: function (data) {
alert(data);
}
});
}
I hope this will work for you perfectly.
I think you need to add the origin URL/IP in CORS setting as well in salesforce if you are making a request from Javascript app so it can get access to salesforce data.

Trouble passing custom headers in a CORS GET request using jquery

I wrote a Web API which need to be accessed outside of the app domain. I have CORS enabled and I'm able to make the API call from outside the application domain. I'm trying to pass in custom HTTP headers as part of the GET request which I'm not able to get it working
I searched in web to get it working but unable to. I'm trying pass in two parameters appId as custom header on a GET request to the web API call using jQuery $.ajax.
url: "http://localhost:38994/api/Search/GetSearchResults",
type: 'GET',
dataType: 'json',
headers: { 'appId': '234' },
data: { param1: 1, param2: { search_by_param: 'xyz', category: 'null'}},
success: function (result) {
alert(result);
}
, error: function (err) { alert(err); }
I tried to use beforeSend to add the headers as well. Regardless I use 'headers' or beforeSend to add headers, I see the custom header names are added to 'Access-Control-Request-Headers' as
Access-Control-Request-Headers: accept, appId
I tried to use JSONP as well using WebApiContrib.Formatting.Jsonp from Nuget. After I add the reference, my project goes for a toss. I see 'dll version mismatch on System.Web.Http.dll between ver 4.0 and 5.0'
Can anyone advice me on how to pass custom Http headers in CORS? Note that when I try to pass custom http headers within my application, it works

How can I use make HTTP calls to an API in Javascript?

How can I use public APIs in a Javascript application? For example I want to make a call to the Zillow API using JQuery AJAX.
When issuing the request in JQuery AJAX (shown below) I get the following error:
XMLHttpRequest cannot load "MY HTTP REQUEST URL". Origin "MY WEB DOMAIN" is not allowed by Access-Control-Allow-Origin.
var requesturl = "http://www.zillow.com/webservice/GetRegionChildren.htm?zws-id="+zwsid+"&state="+state+"&city="+city+"&childtype=neighborhood";
Code:
var jqxhr = $.ajax({
url: requesturl
})
.done(function(data) {
console.log(data);
});
I've also tried adding crossDomain, dataType and headers params (shown below), but they haven't helped.
var jqxhr = $.ajax({
url: requesturl,
crossDomain: true,
dataType: 'xml',
headers: { 'Access-Control-Allow-Origin': '*' },
beforeSend: setHeader
})
.done(function(data) {
console.log(data);
});
Most popular public API's support JSONP request. Refer API documentation for details.
Cross ajax domain request is restricted. So you will be needing to make JSONP request. Don't worry JQuery will handle most of it.
Sounds like you need to register your url with Zillow, maybe contact them / hunt around on their doc pages. Also jquery has a get method which makes ajax requests even simpler. There's also getJSON if that is the return format.

Categories