How to check if GET or POST request?

How can I check if a current request is GET or POST?

You can get the method form the connection. Check the Plug.Conn documentation to see all the fields included:

https://hexdocs.pm/plug/Plug.Conn.html#content

That gets resolved by Phoenix.Router.

in router.ex:

get "/pages/:page", PageController, :show

i.e. a GET request is routed to PageController.show

post "/pages/:page", PageController, :create

a POST request is routed to PageController.create

so in PageController.show you know you are dealing with a GET request and in PageController.create you know you are dealing with a POST request.

get "/pages/:page", PageController, :aaa
post "/pages/:page", PageController, :aaa

Why would you route both GET and POST to PageController.aaa?

If there is any commonality between processing GET and POST, factor that logic out as separate function(s) that both PageController.show and PageController.create can use - while maintaining separate contexts of processing a GET or POST request.

3 Likes

Re-read my original question.