LoginSignup
57
55

More than 3 years have passed since last update.

request-promiseを使ったHTTPクライアントを作る

Last updated at Posted at 2016-04-07

ライブラリがdeprecateされたので他のライブラリを使いましょう

node-fetchあたりとか。

はじめに

request-promiseとは?

  • requestをbluebirdでpromise化したもの
  • Requestプロジェクトに正式に入っている
  • browserifyでブラウザでも使える
  • cheerioなどのパーサーとも組み合わせやすい
  • promiseなのでrest-apiをモジュール化しやすい
  • ベースがrequestなのでrequestの最新版の機能がそのまま使える
  • ”NODE_DEBUG=request node script.js” でリクエスト内容のデバッグができる

install

npm i request-promise

USAGE

GETの簡単な例

var rp = require('request-promise');
rp('http://www.google.com')
    .then(function (htmlString) {
        // Process html...
    })
    .catch(function (err) {
        // Crawling failed...
    });

ステータスコード

404エラーなどのハンドリング

var rp = require('request-promise');
rp('http://www.google.com')
    .then(function (htmlString) {
        // Process html...
    })
    .catch(function (err) {
        switch(err.statusCode){
        case 404:
            // NOT FOUND Process
            break;
        default:
            // Other Error Process
            break;
        }
    });

パーサーを使ってモジュール化する例

jsonの場合

  • optionsに{json : true}でもJSONパースできるがこの場合例外キャッチできないのでtransformを使ったほうが安全(パースできないとテキストとして解釈する?)
var rp = require('request-promise');

var jsonget = function(uri){
    var options = {
        uri: uri,
        transform2xxOnly: true, // ステータスコード200以外のときにHTMLページを帰す場合はtrueにする
        transform: function (body) {
            return JSON.parse(body);
        },
    };
    return rp(options);
}
jsonget('https://raw.githubusercontent.com/nodejs/node/0928584444ac6edf1ead0b93c9d05b1124183702/deps/npm/package.json')
    .then(function (json) {
        // Process json...
    })
    .catch(function (err) {
        // Crawling failed...
    });

yamlの場合

var rp = require('request-promise');
var yaml = require('js-yaml');

var yamlget = function(uri){
    var options = {
        uri: uri,
                transform2xxOnly: true, // ステータスコード200以外のときにHTMLページを帰す場合はtrueにする
        transform: function (body) {
            return yaml.safeLoad(body);
        },
    };
    return rp(options);
}
yamlget('https://raw.githubusercontent.com/ansible/ansible-examples/master/lamp_simple/site.yml')
    .then(function (yaml) {
        // Process yaml...
    })
    .catch(function (err) {
        // Crawling failed...
    });

GETオプションを指定する

var options = {
    uri: "https://api.github.com/user/repos", // URL
    method: "GET",
    timeout: 30 * 1000, // タイムアウト指定しないと帰ってこない場合がある
    qs: { // query string
        access_token: 'xxxxx xxxxx' // -> uri + '?access_token=xxxxx%20xxxxx'
    },
    headers: { // header
        'User-Agent': 'Request-Promise'
    },
}

POSTの簡単な例

HTML FORMにPOSTする

var options = {
    method: 'POST',
    uri: 'http://posttestserver.com/post.php',
    timeout: 30 * 1000, // タイムアウト指定しないと帰ってこない場合がある
    form: {
        name: 'hoge hogeo', // urlencodeされる
        address: 'hoge city',
    },
    headers: {
        /* 'content-type': 'application/x-www-form-urlencoded' */ // ヘッダはデフォルトでapplication/x-www-form-urlencodedが適用されるのでセットしなくてもよい
    }
};

rp(options)
    .then(function (body) {
        // POST succeeded...
    })
    .catch(function (err) {
        // POST failed...
    });

※戻りがJSONの場合はtransformにJSON.parse処理を入れる

JSONでPOSTする

var options = {
    method: 'POST',
    uri: 'http://posttestserver.com/post.php',
    json: {
        name: 'hoge hogemi',
        address: 'secret',
    },
};

rp(options)
    .then(function (parsedBody) {
        // 戻りも自動でJSONパースされる
        // POST succeeded...
    })
    .catch(function (err) {
        // POST failed...
    });
57
55
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
57
55