Adding pagesで新しくページを追加するところまでを学んでいるうちに、Postリクエストを処理する内容に寄り道したのでメモを残しておく
ルーティング
- 基本は
method "path", Controller, :action_name
をweb/router.exに設定していく - resourcesを使うと、GET / POST / PUT / DELETEをまとめてルーティングしてくれたりする
defmodule HelloPhoenix.Router do
use HelloPhoenix.Web, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", HelloPhoenix do
pipe_through :browser # Use the default browser stack
get "/", PageController, :input
post "/hello", PageController, :hello
end
# Other scopes may use custom stacks.
# scope "/api", HelloPhoenix do
# pipe_through :api
# end
end
Controller編集
helloアクションを追加
defmodule HelloPhoenix.PageController do
use HelloPhoenix.Web, :controller
def index(conn, _params) do
render conn, "index.html"
end
def input(conn, _params) do
render conn, "input.html"
end
def hello(conn, %{"messenger" => messenger}) do
render conn, "hello.html", messenger: messenger
end
end
テンプレート編集
<div class="jumbotron">
<h2>Welcome to Phoenix! Hi, <%= @messenger %></h2>
<p class="lead">A productive web framework that<br />does not compromise speed and maintainability.</p>
</div>
はまったこと
CSRFのエラー
invalid CSRF (Cross Site Forgery Protection) token, make sure all requests include a '_csrf_token' param or an 'x-csrf-token' header
解決方法がいくつかあったのですが、自分がうまくいった方法をかいておきます
phoenixのv1.0.0
- Viewでcsrf_tokenを取得するメソッドをインポート
defmodule HelloPhoenix.PageView do
use HelloPhoenix.Web, :view
import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1]
end
- データをPOSTするフォームを用意
- formタグの宣言にPhoenixのテンプレート機能を使っている
<%= form_tag("/hello", method: :post) %>
<input type="text" name="messenger">
<input type="submit" value="enter">
</form>
トップページでPOSTした名前が/helloページで表示されるようになります