Phoenix Route going to wrong route

In my router.ex I have this section

  scope "/auth", TrendingWeb do
    pipe_through [:browser]

    get "/:provider", AuthController, :request
    get "/:provider/callback", AuthController, :callback
    post "/:provider/callback", AuthController, :callback
    post "/logout", AuthController, :logout
  end

In AuthController file. I have this

  def logout(conn, params) do

    conn
    |> put_flash(:info, "You have been logged out!")
    |> configure_session(drop: true)
    |> redirect(to: "/")
  end

And in my template file i have this link tag

            <%= link to: Routes.auth_path(@conn, :logout), method: :post, class: "reg-link" do %>
                 Logout
            <% end %>

When i run mix phx.routes. I get the following output

            auth_path  GET     /auth/:provider                        TrendingWeb.AuthController :request
            auth_path  GET     /auth/:provider/callback               TrendingWeb.AuthController :callback
            auth_path  POST    /auth/:provider/callback               TrendingWeb.AuthController :callback
            auth_path  POST    /auth/logout                           TrendingWeb.AuthController :logout

When i click on the link tag it is taking me to this route

http://localhost:4000/auth/logout

But it is not going to the logout method in the AuthController file. It goes to the wrong route
get "/:provider", AuthController, :request

I am getting this output in the terminal

[info] GET /auth/logout
[debug] Processing with TrendingWeb.AuthController.request/2
  Parameters: %{"provider" => "logout"}
  Pipelines: [:browser]

If anyone can give me the insight on fixing this bug will be greatly appreciated.Thanks.

When you navigate to the http://localhost:4000/auth/logout route, you’re issuing a GET request, as the terminal output reflects: [info] GET /auth/logout. This is hitting the /:provider route because there is no GET /auth/logout route provided.

Try curling (curl -XPOST http://localhost:4000/auth/logout) and it should hit the correct route.

The method: :post option in the call to link/2 (imported from Phoenix.HTML.Link) depends on a JavaScript hook to transform the link from a GET request into a POST request. It seems you are missing the JS dependency, or your browser has JS disabled.

https://hexdocs.pm/phoenix_html/Phoenix.HTML.Link.html#link/2-javascript-dependency

4 Likes

JS enabled only.

I manually inserted the phoenix_html.js in my app.html

  <script src="<%= Routes.static_path(@conn, "/js/jquery.min.js") %>"></script>
  <script src="<%= Routes.static_path(@conn, "/js/bootstrap.min.js") %>"></script>
  <script src="<%= Routes.static_path(@conn, "/js/owl.carousel.min.js") %>"></script>
  **<script src="<%= Routes.static_path(@conn, "/js/phoenix_html.js") %>"></script>**

After this it is working fine. Thanks for your time and help Voltone.