11
11

More than 5 years have passed since last update.

Mithril.js と Phoenixで作ったAPIを連携

Posted at

やること

Mithril.jsからPhoenix(Elixir)で作ったAPIにリクエストを投げてjsonレスポンスを取得する

APIサイド

APIの作成はmixコマンドから

慣れてるということでDBはMySQLを利用
本のタイトルと画像を返却するAPIを作るので、その通りのjsonレスポンスを返すようにコマンドから作る(3行目)
最後にmigrateすると合わせたテーブルが出来る。

$ mix phoenix.new api --database mysql
$ mix ecto.create
$ mix phoenix.gen.json Book books title:string img_url:string
$ mix ecto.migrate

これで下記のURLにリクエストをかけるとデータが返ってくるAPIが出来る。

http://localhost:4000/api/book/1

データを仮で入れてから
curlでリクエストを投げて、レスポンスがちゃんと返ってくるのを確認。

$ curl -H "Content-Type: application/json" http://192.168.33.10:4000/api/books/1
{"data":{"title":"本のタイトル","img_url":"http://img.url.jp/img.jpg","id":1}}

クライアントサイド

MithrilのModel。 Book.read()を呼ぶとAPIからデータを取得してBookインスタンスを生成して返却する。

book.js
var Book = function(data) {
  this.title = m.prop(data.title);
  this.img   = m.prop(data.img);
};

Book.read = function() {
  return m.request({method: "GET", url: "http://localhost:4000/api/books/1"})
    .then(function (jsonData) {
      return new Book({title: jsonData.data.title, img: jsonData.data.img_url});
    });
};

実際に実行すると下記のようなエラーが発生。(クライアントサイドはlocalhost:3000から配信)
クロスドメインのリクエストは許可されておらずリクエストが弾かれた。
許可設定をサーバサイドでしてあげないといけない。

XMLHttpRequest cannot load http://localhost:4000/api/books/1. The 'Access-Control-Allow-Origin' header has a value 'http://localhost:4000' that is not equal to the supplied origin. Origin 'http://localhost:3000' is therefore not allowed access.

下記を参考にPhoenix側に処理を追加する
参考: http://www.leighhalliday.com/cors-in-phoenix

APIサイド

まず、上記参考のライブラリを導入。

mixの設定ファイル。最後にcors_plugを入れる

mix.exs
  defp deps do
    [{:phoenix, "~> 1.0.3"},
     {:phoenix_ecto, "~> 1.1"},
     {:mariaex, ">= 0.0.0"},
     {:phoenix_html, "~> 2.1"},
     {:phoenix_live_reload, "~> 1.0", only: :dev},
     {:cowboy, "~> 1.0"},
     {:cors_plug, "~> 0.1.4"}]
  end

上記を追加したら下記のコマンドでライブラリが追加される

$ mix deps.get

追加したらrouter.exのAPI用pipelineにCORSPlugのplugを追加。
originを指定するとheaderに Access-Control-Allow-Originが追加される。今回は作ったクライアントサイドから見れればいいので、下記のように指定。

router.ex
pipeline :api do
    plug CORSPlug, [origin: "http://localhost:3000"]
    plug :accepts, ["json"]
  end

これで mix phoenix.server で再起動をかければめでたくクライアントサイドからAPIが叩けましたー!

11
11
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
11
11