Provided that your setup is a basic application with no Ecto backing it, this will be the set of changes that you’ll need to introduce in Phoenix 1.6.x
- Create our new controller for
GET
and POST
routes:
# lib/example_web/controller/register_controller.ex
defmodule ExampleWeb.RegisterController do
use ExampleWeb, :controller
def index(conn, _params) do
# While your NodeJS version is simple, it is vulnerable to
# CSRF attacks. You should use the Phoenix forms that handle
# this for you.
# This is enforced by the `:protect_from_forgery` plug
# defined in our router
csrf_token = Plug.CSRFProtection.get_csrf_token()
render(conn, "form.html", [csrf_token: csrf_token])
end
def register(conn, params) do
# %{"example" => "User provided value", "_csrf_token" => "token_value"}
IO.inspect(params, label: "Form params")
redirect(conn, to: "/register")
end
end
- Create out view module. Our view module could be used to expose shared logic in our templates:
# lib/example_web/views/register_view.ex
defmodule ExampleWeb.RegisterView do
use ExampleWeb, :view
end
- Add our template:
# lib/example_web/templates/register/form.html.heex
<form method="POST" action="/register">
<input type="hidden" name="_csrf_token" value={@csrf_token} />
<input type="text" name="example" />
<input type="submit">
</form>
- Finally, wire it up in our router:
# lib/example_web/router.ex
defmodule ExampleWeb.Router do
use ExampleWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {ExampleWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
scope "/", ExampleWeb do
pipe_through :browser
get "/", PageController, :index
get "/register", RegisterController, :index # To view the form
post "/register", RegisterController, :register # To submit the form
end
end
I know there’s a lot more here that your NodeJS example. In your example, the templating part is completely omitted and doesn’t include CSRF attack prevention. It might seem like a lot of ceremony in comparison, but keep in mind that Express isn’t a full stack web framework and Phoenix is. A majority of NodeJS full stack frameworks (e.g. NestJS) have this sort of rigmarole.