Estoy creando una aplicación web de una sola página que realiza una solicitud AJAX a Flickr (usando la API de Flickr). Cuando intento la solicitud usando curl o cartero, funciona. Cuando lo pruebo desde Chrome usando AJAX (jQuery), recibo una respuesta de 200 con un estado de "OK", pero siempre 0 resultados. Si tomo exactamente la misma URL (literalmente copiar y pegar) en cartero / curl obtengo resultados. Debo estar haciendo algo tonto, pero no puedo entenderlo.

Código JavaScript:

var photoQueryURL = 'https://api.flickr.com/services/rest/?' + $.param({
    'method': 'flickr.photos.search',
    'api_key': flickrAPIKey,
    'text': title,
    'tags': title,
    'format': 'json',
    'nojsoncallback': '1'
});
// AJAX Query:
$.ajax(photoQueryURL)
    .done(function(data) {
        console.log('Sucessful query.');
        console.log(data);
    })
    .fail(function(err) {
        console.log('Failed query.');
        console.log(err);
    });

Consulta AJAX:

Request URL:https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=<my-key>&text=Alex%27s%20Pizzeria&tags=Alex%27s%20Pizzeria&format=json&nojsoncallback=1
Request Method:GET
Status Code:200 
Remote Address:69.147.64.33:443
Referrer Policy:no-referrer-when-downgrade
Response Headers
access-control-allow-origin:*
age:2
cache-control:private
content-encoding:gzip
content-length:83
content-type:application/json
date:Sat, 28 Oct 2017 21:59:02 GMT
p3p:policyref="https://policies.yahoo.com/w3c/p3p.xml", CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE LOC GOV"
server:ATS
status:200
vary:Accept-Encoding
via:http/1.1 fts126.flickr.bf1.yahoo.com (ApacheTrafficServer [cMsSf ]), http/1.1 e22.ycpi.cha.yahoo.com (ApacheTrafficServer [cMsSf ])
x-content-type-options:nosniff
x-frame-options:SAMEORIGIN
x-served-by:www-bm006.flickr.bf1.yahoo.com
Request Headers
:authority:api.flickr.com
:method:GET
:path:/services/rest/?method=flickr.photos.search&api_key=<my-key>&text=Alex%27s%20Pizzeria&tags=Alex%27s%20Pizzeria&format=json&nojsoncallback=1
:scheme:https
accept:application/json, text/javascript, */*; q=0.01
accept-encoding:gzip, deflate, br
accept-language:en-US,en;q=0.9
cache-control:no-cache
origin:null
pragma:no-cache
user-agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36
Query String Parameters
view source
view URL encoded
method:flickr.photos.search
api_key:<my-key>
text:Alex's Pizzeria
tags:Alex's Pizzeria
format:json
nojsoncallback:1

Respuesta AJAX:

{"photos":{"page":1,"pages":0,"perpage":100,"total":"0","photo":[]},"stat":"ok"}

Consulta con rizo:

curl -k "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=<my-key>&text=Alex%27s%20Pizza&tags=Alex%27s%20Pizza&format=json&nojsoncallback=1"

Respuesta (aviso 5 resultados):

{"photos": {"page": 1, "pages": 1, "perpage": 100, "total": "5",
"photo": [{"id":(...)}]},
"stat":"ok"}

¿Sugerencias?

--Jim

0
James S. 29 oct. 2017 a las 01:10

3 respuestas

La mejor respuesta

Tu código es correcto He creado una cuenta de Flickr para reproducir su problema.

Agregué este código para imprimir los resultados:

var len = data.photos.photo.length, html = "";
if (len > 0) {
  var i;
  for (i = 0; i < len; i++) {
    html += "<li>";
    html += data.photos.photo[i].title;
    html += "</li>";
  }
  $("#list").html(html);
}

Algo como esto:

(function() {
  $("#form").on("submit", function(e) {
    var flickrAPIKey = "39417c145483a7fb3ee91c5fe5bc93fe",
      title = $("#txtInput").val();
    var photoQueryURL = 'https://api.flickr.com/services/rest/?' + $.param({
      'method': 'flickr.photos.search',
      'api_key': flickrAPIKey,
      'text': title,
      'tags': title,
      'format': 'json',
      'nojsoncallback': '1'
    });
    // AJAX Query:
    $.ajax(photoQueryURL)
      .done(function(data) {
        console.log('Sucessful query.');
        var len = data.photos.photo.length, html = "";
        if (len > 0) {
          var i;
          for (i = 0; i < len; i++) {
            html += "<li>";
            html += data.photos.photo[i].title;
            html += "</li>";
          }
          $("#list").html(html);
        }
      })
      .fail(function(err) {
        console.log('Failed query.');
        console.log(err);
      });
    e.preventDefault();
  });
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="form">
  <label for="txtInput">Input:</label>
  <input id="txtInput" type="text" />
  <button type="submit">Send</button>
  <hr />
  <ul id="list"></ul>
</form>

El encabezado Access-Control-Allow-Origin: * está presente.

enter image description here

1
Danny Fardy Jhonston Bermúdez 31 oct. 2017 a las 14:24
$(function() {
  //store public feed in URL
  var URL = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
  //create searchInfo object
  var searchInfo = {
    
    tags : $('#searchfield').val(),
    tagmode : "any",
    format : "json"
  };
  //when search button is clicked
  $('#searchbtn').click(function(){
    //update the search info object
    searchInfo.tags = $('#searchfield').val();
    //get JSON
    $.getJSON(URL,searchInfo,function(data){
        var photoHTML = '';
        //loop through each photo object
        $.each(data.items, function(i, photo) {
          photoHTML += '<span class ="image">';
          photoHTML += '<a href="' + photo.link 
                        + '">';
          photoHTML += '<img src ="' +         photo.media.m.replace('_m','_s')+'"></a></span>';
         
       });// end each
     
      //add the HTML to the page
     $('#images').append(photoHTML);
       
      
    }); // end get JSON
    
  }); //end click
  
}); //end ready
.image {
  padding: 10px;
  margin: 0 30px 30px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <title>Flickr Search for example kitten :)</title>
  </head>
  <body>
    <h1>Flickr Search</h1>
    <h4>Search for any image here!</h4>
    <input type="text" id="searchfield" />
    <button id ="searchbtn">Search</button>
    
    <div id="images">
    </div>
  </body>
</html>
0
user8556290user8556290 28 oct. 2017 a las 23:11
/*

  Create an api to get an API KEY here:
  https://www.flickr.com/services/apps/create/

  Documentation for searching photos:
  https://www.flickr.com/services/api/flickr.photos.search.html

  */

  $('.fetch-button').click(function() {
    var $button = $(this);
    var photoUrl;

    $button.text('Loading...'); // Set text of button to loading
    $button.attr('disabled', 'disabled'); // Disable button
    $('.output').empty(); // Clear out results
    
    //what you are looking for
    var lookingfor = $('#wording').prop('value');
    var perpage = $('#per_page').prop('value');
    var page = $('#page').prop('value');
    var lowlang = $('#lang').prop('value');
    var lang = lowlang.toLowerCase() + '-' + $('#lang').prop('value');
    var api_key = 'e0246bb8460f3650cef44a21d89d4c60';
    var sort = $('#sort').prop('value');
    var content_type = $('#content_type').prop('value');
    
    
    
    console.log(lang)
    
    $.ajax({
      method: 'GET',
      url: 'https://api.flickr.com/services/rest?sort=' + sort + '&parse_tags=1&content_type=' + content_type + '&extras=can_comment,count_comments,count_faves,description,isfavorite,license,media,needs_interstitial,owner_name,path_alias,realname,rotation,url_c,url_l,url_m,url_n,url_q,url_s,url_sq,url_t,url_z&per_page=' + perpage + '&page=' + page + '&lang=' + lang + '&text=' + lookingfor + '&viewerNSID=&method=flickr.photos.search&csrf=&api_key=' + api_key + '&format=json&hermes=1&hermesClient=1&reqId=e626c8a6&nojsoncallback=1'
    }).done(function(data) {
      console.log(data);
      if (!data.photos) {
        return;
      }
      $.each(data.photos.photo, function(key, photo) {
        photoUrl = 'https://farm' +
          photo.farm +
          '.staticflickr.com/' +
          photo.server +
          '/' +
          photo.id +
          '_' +
          photo.secret +
          '_q.jpg';
        $('.output').append('<img src="' + photoUrl + '">');
      });

    }).always(function() {
      $button.text('Fetch Data'); // Reset button text
      $button.removeAttr('disabled'); // Enable button to be clicked again
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div class="wrapper">
  <h1>Flickr API own by fetching all call rest api</h1>
  <input placeholder="search" id="wording" type="text" value="" name="search"/>
  <input placeholder="user_id" id="user_id" type="text" value="" name="user_id"/>
  <input placeholder="tags" id="tags" type="text" value="" name="tags"/>
  <input placeholder="tag_mode" id="tag_mode" type="text" value="" name="tag_mode"/>
  <input placeholder="text" id="text" type="text" value="" name="text"/>
  <input placeholder="min_upload_date" id="min_upload_date" type="text" value="" name="min_upload_date"/>
  <input placeholder="max_upload_date" id="max_upload_date" type="text" value="" name="max_upload_date"/>
  <input placeholder="min_taken_date" id="min_taken_date" type="text" value="" name="min_taken_date"/>
  <input placeholder="max_taken_date" id="max_taken_date" type="text" value="" name="max_taken_date"/>
  <input placeholder="license" id="license" type="text" value="" name="license"/>
  <input placeholder="sort" id="sort" type="text" value="relevance" name="sort"/>
  <input placeholder="privacy_filter" id="privacy_filter" type="text" value="" name="privacy_filter"/>
  <input placeholder="bbox" id="bbox" type="text" value="" name="bbox"/>
  <input placeholder="accuracy" id="accuracy" type="text" value="" name="accuracy"/>
  <input placeholder="safe_search" id="safe_search" type="text" value="" name="safe_search"/>
  <input placeholder="content_type" id="content_type" type="text" value="7" name="content_type"/>
  <input placeholder="machine_tags" id="machine_tags" type="text" value="" name="machine_tags"/>
  <input placeholder="machine_tag_mode" id="machine_tag_mode" type="text" value="" name="machine_tag_mode"/>
  <input placeholder="group_id" id="group_id" type="text" value="" name="group_id"/>
  <input placeholder="contacts" id="contacts" type="text" value="" name="contacts"/>
  <input placeholder="woe_id" id="woe_id" type="text" value="" name="woe_id"/>
  <input placeholder="place_id" id="place_id" type="text" value="" name="place_id"/>
  <input placeholder="media" id="media" type="text" value="" name="media"/>
  <input placeholder="has_geo" id="has_geo" type="text" value="" name="has_geo"/>
  <input placeholder="geo_context" id="geo_context" type="text" value="" name="geo_context"/>
  <input placeholder="lat" id="lat" type="text" value="" name="lat"/>
  <input placeholder="lon" id="lon" type="text" value="" name="lon"/>
  <input placeholder="radius" id="radius" type="text" value="" name="radius"/>
  <input placeholder="radius_units" id="radius_units" type="text" value="" name="radius_units"/>
  <input placeholder="is_commons" id="is_commons" type="text" value="" name="is_commons"/>
  <input placeholder="in_gallery" id="in_gallery" type="text" value="" name="in_gallery"/>
  <input placeholder="is_getty" id="is_getty" type="text" value="" name="is_getty"/>
  <input placeholder="extras" id="extras" type="text" value="" name="extras"/>
  <input placeholder="per_page" id="per_page" type="text" value="25" name="per_page"/>
  <input placeholder="page" id="page" type="text" value="1" name="page"/>
  <select id="lang" name="lang" data-placeholder="Choose a Language...">
  <option value="AF">Afrikanns</option>
  <option value="SQ">Albanian</option>
  <option value="AR">Arabic</option>
  <option value="HY">Armenian</option>
  <option value="EU">Basque</option>
  <option value="BN">Bengali</option>
  <option value="BG">Bulgarian</option>
  <option value="CA">Catalan</option>
  <option value="KM">Cambodian</option>
  <option value="ZH">Chinese (Mandarin)</option>
  <option value="HR">Croation</option>
  <option value="CS">Czech</option>
  <option value="DA">Danish</option>
  <option value="NL">Dutch</option>
  <option value="EN" selected>English</option>
  <option value="ET">Estonian</option>
  <option value="FJ">Fiji</option>
  <option value="FI">Finnish</option>
  <option value="FR">French</option>
  <option value="KA">Georgian</option>
  <option value="DE">German</option>
  <option value="EL">Greek</option>
  <option value="GU">Gujarati</option>
  <option value="HE">Hebrew</option>
  <option value="HI">Hindi</option>
  <option value="HU">Hungarian</option>
  <option value="IS">Icelandic</option>
  <option value="ID">Indonesian</option>
  <option value="GA">Irish</option>
  <option value="IT">Italian</option>
  <option value="JA">Japanese</option>
  <option value="JW">Javanese</option>
  <option value="KO">Korean</option>
  <option value="LA">Latin</option>
  <option value="LV">Latvian</option>
  <option value="LT">Lithuanian</option>
  <option value="MK">Macedonian</option>
  <option value="MS">Malay</option>
  <option value="ML">Malayalam</option>
  <option value="MT">Maltese</option>
  <option value="MI">Maori</option>
  <option value="MR">Marathi</option>
  <option value="MN">Mongolian</option>
  <option value="NE">Nepali</option>
  <option value="NO">Norwegian</option>
  <option value="FA">Persian</option>
  <option value="PL">Polish</option>
  <option value="PT">Portuguese</option>
  <option value="PA">Punjabi</option>
  <option value="QU">Quechua</option>
  <option value="RO">Romanian</option>
  <option value="RU">Russian</option>
  <option value="SM">Samoan</option>
  <option value="SR">Serbian</option>
  <option value="SK">Slovak</option>
  <option value="SL">Slovenian</option>
  <option value="ES">Spanish</option>
  <option value="SW">Swahili</option>
  <option value="SV">Swedish </option>
  <option value="TA">Tamil</option>
  <option value="TT">Tatar</option>
  <option value="TE">Telugu</option>
  <option value="TH">Thai</option>
  <option value="BO">Tibetan</option>
  <option value="TO">Tonga</option>
  <option value="TR">Turkish</option>
  <option value="UK">Ukranian</option>
  <option value="UR">Urdu</option>
  <option value="UZ">Uzbek</option>
  <option value="VI">Vietnamese</option>
  <option value="CY">Welsh</option>
  <option value="XH">Xhosa</option>
</select>
 
  
  <button class="fetch-button">Fetch Data</button>
  <div class="output">
  </div>
</div>
0
31 oct. 2017 a las 12:39