8
6

More than 5 years have passed since last update.

SuperAgent(HTTPリクエスト用のNode.jsモジュール)の使い方メモ

Last updated at Posted at 2015-06-05

SuperAgent は HTTPリクエストをするための Node.js モジュール。

Browserify や webpack 等を利用すればブラウザでも利用できると思われる。

ブラウザ向けでいうと、jQueryを使わずに Ajax 的なことをしたい場合に。

導入方法

npm コマンドでいれる。

$ npm install [--save|--save-dev] superagent

HTTPリクエストの例

例えば Qiia API(v1) にアクセスして新着投稿のタイトルを取得するのは次のように書ける。

var request = require('superagent');

var URL = 'http://qiita.com/api/v1/items/?per_page=5';

request
  .get(URL)
  .end(function(err, res) {
    if (res.ok) {
      //console.log(res.status); // HTTPレスポンスのステータスコード
      res.body.forEach(function(item) { // HTTPレスポンスBody(JSON)の配列を1件づつ処理
        console.log(item.title);
      });
    } else {
      console.log('error');
    }
  });
8
6
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
8
6