JSONのmockサーバの構築メモ。 grunt-connect-proxy, grunt-stubbyを利用してAjax用のJSON(モックデータ)を取得する[grunt] ココ参考にさせてもらいました!!ありがとうございます。
npm install grunt-stubby --save-dev
mkdir -p grunt mkdir -p mocks/stubby/hoge
cat grunt/stubby.js
'use strict'; module.exports = function (grunt) { grunt.config('stubby', { stubsServer: { // note the array collection instead of an object options: { callback: function (server, options) { server.get(1, function (err, endpoint) { if (!err) { console.log(endpoint); } }); }, stubs: 3000, tls: 8443, admin: 8010, location: '0.0.0.0', persistent: true }, files: [{ src: ['mocks/stubby/**/*.yaml'] }] } }); };
gruntから起動するため Gruntfile.js に
grunt.loadTasks('grunt');
と記述*1。
cat mocks/stubby/hoge.yaml
- request: url: ^/ajax/hoge/$ method: GET response: - status: 200 headers: content-type: application/json file: mocks/stubby/hoge/get.json
cat mocks/stubby/hoge/get.json
{ "foo":"1", "bar":"2" }
grunt stubby
REST なクライアント*2やブラウザから
http://localhost:3000/ajax/hoge/
へアクセスするとJSONデータが取得できましたー。。
grunt serveで起動するために serveのタスクに追加します。
grunt.task.run([ 'clean:server', 'wiredep', 'concurrent:server', 'autoprefixer:server', 'connect:livereload', 'stubby', ←追加 'watch' ]);
https://github.com/masatomix/ui-router-sample/commit/1347af60619368d0eb34731e6d58cbc1ba61ce31
gruntが起動したWEBサーバから、Stubbyで起動したmockサーバにreverse proxyする設定を追加します。というのは、JavaScript?は基本的には別サーバのJSONにはアクセスできない*3つまりgruntのWEBサーバから落としてきたJavaScript?はgruntのJSONにしかアクセスできないので、Stubbyが動いてるmockサーバのJSONに直接アクセスすることはできません。従って、いったんgruntのWEBサーバにアクセスしてreverse proxyする必要があるわけです。
gruntのWEBサーバの /hoge/fuga.json -- proxy --> stubbyの /hoge/fuga.json
つまりこういうことです。
grunt-connect-proxyのめも - yamashiro0110の日記 ココを参考にさせてもらいました。ありがとうございます!!
npm install grunt-connect-proxy --save-dev
ココの下あたりに一行追加。
// Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;
続いて connect.livereload.middleware あたりに以下を追加。あとproxiesの設定も追加。
// The actual grunt server settings connect: { options: { 割愛 }, proxies: [ { // `localhost:9000/ajax`へのリクエストは`localhost:3000/ajax`へプロキシされるようになる context: '/ajax/', host: 'localhost', port: 3000 } ], // ↑このproxies配列追加 livereload: { options: { open: true, middleware: function (connect) { return [ proxySnippet, ←ココ追加 connect.static('.tmp'), ... いろいろ書いてあったけど割愛。。。 ]; } } }, ... 以下省略。
最後に grunt serve で起動するためのserveのタスクに追加。
grunt.task.run([ 'clean:server', 'wiredep', 'concurrent:server', 'configureProxies', ←ココ追加。 'autoprefixer:server', 'connect:livereload', 'stubby', 'watch' ]); });
grunt serve したあと、
http://localhost:9000/ajax/hoge/
へアクセスしてさっきのJSONデータが取れれば成功です。。
お疲れ様でした。
https://github.com/masatomix/ui-router-sample/commit/d48210149ddd407ab5bbd4d52b870957db2baea9 なんか勝手に整形されていろいろ差分出ちゃってるけどごめんなさいって感じ(´Д`;)。。
mockとProxy関連。
この記事は
現在のアクセス:5044