LoginSignup
11
11

More than 5 years have passed since last update.

PhoenixでPostリクエストを処理するところまで試した

Posted at
  • phoenixとは、elixirで実装されたWeb framework
  • Getting Startedを進めていくと、いろいろと学べるはず

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ページで表示されるようになります

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