简体   繁体   中英

LastFM API login - CORS Issue

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?

PS - 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM