2015-04-27 追記 SuperAgentの方がよさそう。
jQuery依存から脱するためのJavaScript版HTTPクライアントを探し中。
rest.jsを使ってみる。
CommonJSに対応しているので、browserifyから使う。
プロジェクト作成
- npmインストール前提
- gulpインストール前提(
npm install -g gulp
)
npmプロジェクト設定
$ mkdir restjs-sample
$ cd restjs-sample
$ npm init
Yesマンでこたえる
ビルドに必要なものをインストール
$ npm install --save-dev browserify gulp vinyl-source-stream rest
gulpfile.js作成
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
gulp.task('browserify', function () {
return browserify('./index.js', {debug: true})
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./'));
});
サンプルアプリ作成
index.js
index.js
を以下のように作成
var rest = require('rest');
var mime = require('rest/interceptor/mime');
var client = rest.wrap(mime);
client({path: 'http://blog.ik.am/api/v1/links'}).then(function(response) {
console.log(response);
});
http://blog.ik.am/api/v1/links はCORS対応している。
index.html
<!DOCTYPE html>
<html>
<head lang="ja">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
ビルド
$ gulp browserify
bundle.jsができる。
ブラウザで確認。といっても画面には何も出ないので、コンソール確認
できた。jQueryはいらないけど、Ajaxアクセスはしたいって時に便利かも。
CLIから叩く
実はvar rest = require('rest');
の段階で、HTTPクライアントとして、XMLHttpReqest ClientをつかうかNode Clientを使うか自動で判断する。
(browserifyでビルドするとXMLHttpReqest Clientになる)
というわけで、index.js
をNode.jsから叩いてもそのまま実行できる!
$ node index.js
{ request:
{ path: 'http://blog.ik.am/api/v1/links',
originator:
{ [Function: interceptedClient]
skip: [Function: skip],
wrap: [Function: wrap],
chain: [Function: chain] },
headers:
{ 'Content-Type': 'text/plain',
Accept: 'text/plain, application/json;q=0.8, text/plain;q=0.5, */*;q=0.2' },
method: 'GET',
canceled: false,
cancel: [Function: cancel] },
raw:
{ request:
{ domain: null,
_events: [Object],
_maxListeners: 10,
output: [],
outputEncodings: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_headerSent: true,
_header: 'GET /api/v1/links HTTP/1.1\r\nContent-Type: text/plain\r\nAccept: text/plain, application/json;q=0.8, text/plain;q=0.5, */*;q=0.2\r\nContent-Length: 0\r\nHost: blog.ik.am\r\nConnection: keep-alive\r\n\r\n',
_hasBody: true,
_trailer: '',
finished: true,
_hangupClose: false,
socket: [Object],
connection: [Object],
agent: [Object],
socketPath: undefined,
method: 'GET',
path: '/api/v1/links',
_headers: [Object],
_headerNames: [Object],
parser: null,
res: [Object] },
response:
{ _readableState: [Object],
readable: false,
domain: null,
_events: [Object],
_maxListeners: 10,
socket: [Object],
connection: [Object],
httpVersion: '1.1',
complete: true,
headers: [Object],
trailers: {},
_pendings: [],
_pendingIndex: 0,
url: '',
method: null,
statusCode: 200,
client: [Object],
_consuming: true,
_dumped: false,
httpVersionMajor: 1,
httpVersionMinor: 1,
upgrade: false,
req: [Object],
pipe: [Function],
addListener: [Function],
on: [Function],
pause: [Function],
resume: [Function],
read: [Function] } },
status: { code: 200 },
headers:
{ Date: 'Tue, 03 Mar 2015 13:46:45 GMT',
Server: 'Jetty(8.1.15.v20140411)',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Max-Age': '3600',
'Access-Control-Allow-Headers': 'x-requested-with,x-formatted,x-admin,x-track,accept,authorization,cache-control,content-type,if-modified-since,pragma',
'X-Track': 'c7a4eeb60f1d46809aba94fa6792b2c5',
'X-Application-Context': 'application:cache.hazelcast,db.property:8443',
'Content-Type': 'application/json;charset=UTF-8',
Connection: 'close',
'Transfer-Encoding': 'chunked' },
entity:
[ { id: 'http://bit.ly/hajiboot',
url: 'http://bit.ly/hajiboot',
linkName: 'はじめてのSpring Boot (書きました)' },
{ id: 'http://amzn.to/hajiboo',
url: 'http://amzn.to/hajiboo',
linkName: 'はじめてのBootstrap (書きました)' },
{ id: 'https://github.com/making',
url: 'https://github.com/making',
linkName: 'Github' },
{ id: 'https://twitter.com/making',
url: 'https://twitter.com/making',
linkName: 'Twitter' },
{ id: 'http://qiita.com/making@github',
url: 'http://qiita.com/making@github',
linkName: 'Qiita' },
{ id: 'http://www.slideshare.net/makingx',
url: 'http://www.slideshare.net/makingx',
linkName: 'SlideShare' },
{ id: 'http://ik.am', url: 'http://ik.am', linkName: 'Home' },
{ id: 'http://amzn.to/JavaEE6',
url: 'http://amzn.to/JavaEE6',
linkName: 'Beginning Java EE 6 GlassFish 3で始めるエンタープライズJava (一部翻訳しました)' },
{ id: 'http://chatikam.herokuapp.com/',
url: 'http://chatikam.herokuapp.com/',
linkName: 'CHAT.IK.AM (Markdownが使えるシンプルなマルチチャネルWebSocketチャット)' },
{ id: 'https://blog.ik.am/admin',
url: 'https://blog.ik.am/admin',
linkName: '管理コンソール' } ] }
Interceptor色々噛ませられそうで良い。
React.jsと組み合わせたい。