13
13

More than 5 years have passed since last update.

node.js で Google URL Shortener を使って短縮 URL を作る

Posted at

備忘録です.

ローカルで作ったプロジェクトを runstant 用に出力する grunt タスクを作ってて
そんとき必要になったやつ.

Google の goo.gl を使ってます.

https バージョン

var https = require('https');

var shortenURL = function(url, callback) {
    var req = https.request({
        host: 'www.googleapis.com',
        path: '/urlshortener/v1/url',
        method: 'POST',
        headers: {'Content-Type': 'application/json'},

    }, function(res) {
        var str = '';
        res.on('data', function(chunk) {
            str += chunk.toString();
        });
        res.on('end', function() {
            var d = JSON.parse(str);
            callback(d);
        });
    });

    req.write('{"longUrl" : "' + url + '"}\n');
    req.end();
};

// 実行
shortenURL("http://tmlife.io", function(d) {
    console.log(d.id); // http://goo.gl/pZPJLf
});

request バージョン

https でバカ正直に実装してたのですが,
request モジュールを使えばもっとサクッとやれます.

@kjunichi san のこちらを参考

var request = require('request');

var shortenURL = function(url, callback) {
    request.post({
        url: "https://www.googleapis.com/urlshortener/v1/url",
        headers: {
            'Content-Type': 'application/json'
        },
        json: true,
        body: JSON.stringify({
            longUrl: url
        }),
    }, function(error, response, body) {
        callback(body);
    });
};

shortenURL("http://tmlife.io", function(d) {
    console.log(d.id); // http://goo.gl/pZPJLf
});
13
13
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
13
13