LoginSignup
4
2

More than 5 years have passed since last update.

Google URL Shorter を Node.JSから使用する

Last updated at Posted at 2016-05-26

ゴール

スクリプト(Node.JS)で短縮URLを取得する。

目的

Physical-WEBでURLを送信する場合の文字数制限に対応する為。

環境

raspberry pi2(jessie)
node v0.12.6
npm 2.11.2
nodebrew 0.9.5

手順

(1) goo.glのインストール

https://www.npmjs.com/package/goo.gl
・npmを使って
$ npm install goo.gl
・readmeにあるように
$ goo.gl www.google.com
Google requires an API key. See https://developers.google.com/url-shortener/v1/getting_started#auth
・言われました。そこで…

(2) Google URL Shortner API key の取得

https://developers.google.com/url-shortener/v1/getting_started#auth
・プロジェクトを作成。名前は"Physical-WEB TEST"とした。
・"有効" ⇒ "認証情報に進む" ⇒ プロジェクトへの認証情報の追加ページに飛ぶのでオプションを選んで認証KEYを作成。
$ goo.gl www.google.com -k '認証KEY'
http://www.google.com -> http://goo.gl/fbsS
・上手くいった(^^♪

(3) 実際にNode.JSから使ってみる

$ cat test_shorterUrl.js
var googl = require('goo.gl');

// Set a developer key
googl.setKey('認証KEY');
// Get currently set developper key
googl.getKey();

googl.shorten('https://developers.google.com')
.then(function(shortUrl) {
console.log(shortUrl);
}).catch(function(err) {
console.log(err.message);
});

$ node test_shorterUrl.js
https://goo.gl/DkYLM

結果

・以上で短縮URLを取得することが出来た。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2