weixin_33704591 2015-04-28 06:33 采纳率: 0%
浏览 48

LastFM API登录-CORS问题

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?

  • 写回答

1条回答 默认 最新

  • weixin_33716941 2015-04-28 11:36
    关注

    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);
    
    评论

报告相同问题?