Pomax / node-flickrapi

A node.js (and client-library) implementation of the Flickr API with oauth API key authentication and API method proxying
176 stars 51 forks source link

Flickr.tokenOnly is not getting fired. #103

Closed ckim16 closed 7 years ago

ckim16 commented 7 years ago

Hi,

I'm using react/redux and node.js/flickrapi to create a single webpage but I'm having trouble with fetching photos from flickrapi. I want to use tokenOnly method but I don't think it is going through it since I don't see any consoles that I put.

const express = require('express');
const bodyParser = require('body-parser');
const Flickr = require('flickrapi');
const app = express();
const port = process.env.PORT || 3030;
const {api_key, secret} = require('./apikey');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(function(req, res, next) {
  // Website you wish to allow to connect
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  // Pass to next layer of middleware
  next();
});

const flickrOptions = { api_key, secret };

app.post('/', function(req, res) {
  const { text } = req.body;
  Flickr.tokenOnly(flickrOptions, function(err, flickr) {
    console.log('flickr', flickr);
    flickr.photos.search({
      text,
      content_type: 1,
      per_page: 100,
      page:1
    }, function(err, result) {
      console.log('result', result);
      res.send(result);
    });
  });
});

app.listen(port, () => {
  console.log('Sever is listening on port ', port);
});

I do not see flickr console and result either. Trying to figure out what the problem but I am not making any progress.

Has anyone had similar problem as mine and know how to resolve this?

Pomax commented 7 years ago

Don't set up new instances of the Flickr API every time the route gets called. It's not a constructor, but a full API object builder; call it once, and then bind the flickr instance for use in your own API:

let flickr = false;
let flickrOptions = { api_key, secret };
Flickr.tokenOnly(flickrOptions, function(err, flickrObject) {
  if (err) {
    return console.error(err);
  }
  console.log('flickr', flickrObject);
  flickr = flickrObject;
});

app.post('/', function(req, res) {
  const { text } = req.body;
  if (!flickr) {
    return res.status(500).json({ error: 'flickr not ready yet' });
  }
  flickr.photos.search({
    text,
    content_type: 1,
    per_page: 100,
    page:1
  }, function(err, result) {
    console.log('result', result);
    res.send(result);
  });
});

I don't see an if (err) console.error(err) in your code to check whether the api object creation succeeded or not, so at the very least you'll want to add that in.

ckim16 commented 7 years ago

Sweet it works now. I really appreciate it!!

Pomax commented 7 years ago

no problem, good to hear it works now.