Search code examples
javascriptjquerynode.jsexpressinstagram-api

Requesting data through GET request to express server returns document instead of data


I am trying to use the Instagram api to retrieve some data. The problem is that when sending the data back from the express server to the client, the client doesn't log the data to the console but instead I just get an html document displayed with only one line:

{"urls":["https://scontent.cdninstagram.com/t51.2885-15/s320x320/e35/21042827_129089451063629_713103852630441984_n.jpg"]}

Client side:

$('#retrieve_photos_btn').click(function(){
    $.ajax({
        url: "/retrieve_photos",
        type: "GET",
        success: function(result){
            console.log(result);
        }
    });
});

App.js:

app.get('/retrieve_photos', function(req, res){
    var options = {
        method: 'GET',
        url: 'https://api.instagram.com/v1/users/self/media/recent/?access_token='+access_token
    }
    request(options, function(error, resp, body){
        if(error) console.log("Retrieving photos failed: " + error);
        var body_parsed = JSON.parse(body);

        var media_urls = [];
        // Iterate over all received media
        for(var i = 0; i < body_parsed.data.length; i++){
            media_urls.push(body_parsed.data[i].images.low_resolution.url);
        }
        res.send( JSON.stringify( {urls: media_urls} ) );
    });
});

Solution

  • So I already found the problem: the button was inside a form like this:

    form#retrieve_photos_insta_form(method='GET', action='retrieve_photos')
        button.btn.btn-primary#retrieve_photos_btn Retrieve
    

    So when clicking the button, the call to /retrieve_photos would be done through the form, instead of the javascript code I wrote in the question.

    Changing the code so that there is no form and the button directly triggers the javascript code fixed my problem.