FacebookOpengraphInputNodeJS Open Graph Example

The following NodeJS example shows how a user might use Opengraph.io to get a website’s title, description, and icon given a URL.  This example makes use of ExpressJS to proxy the request from a web user onto the OpenGraph.io API.  This approach is often more appropriate in applications than sending traffic directly to OpenGraph.io’s server in that you have the ability to hide your API token and you can also perform any pre/post processing on the server rather than bogging down the client’s browser.  The need for a function like this is very common when creating an application that posts content onto social media sites such as Facebook (see screenshot to the right) or Linkedin where the user wants to control how the link is displayed.

If you would like more examples of how to use this the OpenGraph API, please check out the README for our node module: https://github.com/primeobsession/opengraph-io

Javascript Code

var opengraph = require('opengraph-io')({appId: 'xxxxxx'}); // <-- Enter your app_id!
var express = require('express');
var app = express();

app.get('/site/info', function (req, res) {
  var siteUrl = req.query['url'];

  opengraph.getSiteInfo(siteUrl, function(err, siteInfo){
    console.log('hey err', err);
    console.log('hey result', siteInfo);
    res.json(siteInfo);
  });

});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
  console.log('Test this proxy with the following url:', 'http://localhost:3000/site/info?url=https%3A%2F%2Fnytimes.com');
});

To get the code above working, create a new directory and change into that directory from the command line (Linux or OSX)

mkdir example & cd example

Next, initialize the node package. Enter the information you are prompted for after entering the following

npm init

Next, install the ExpressJS and https packages

npm install express opengraph-io –save

Finally, start the app up

node server.js

Now that the server is running you should be able to point a local browser to the following url: http://localhost:3000/site/info?url=https%3A%2F%2Fnytimes.com