Another option you have is to define a render function for both an index.html and an index.json and then just pass the action’s atom to the render function in your controller. In other words instead of having render(conn, "index.html"...), you’ll have render(conn, :index...). Here’s an example from one of my apps:
card_controller.ex:
#...
def index(conn, _params) do
cards = Task.list_cards()
render(conn, :index, cards: cards)
end
#...
def show(conn, %{"id" => id}) do
card = Task.get_card!(id)
render(conn, :show, card: card)
end
#...
With this in place, Phoenix will look for the appropriate (view) render function or template for each content type. You could have an index.html.eex, an index.json.eex, an index.xml.eex and even more options all in the same template directory.
What I often do with JSON is just define a render function directly in the view instead of making a template, since it’s so short and Phoenix will automatically use Jason (or whichever encoder you’ve configured) to encode your data properly.
card_view.ex:
defmodule MellowWeb.CardView do
use MellowWeb, :view
def render("index.json", %{cards: cards}), do: cards
def render("show.json", %{card: card}), do: card
end
As @voltone pointed out, you’ll need to make sure your router plug accepts includes JSON and then Phoenix will honor the Accept header coming from the front end.
Using axios (or Vue.axios in my case), you can do that with the headers field like this:
Vue.axios({
method: "POST",
url: "/cards",
data: data,
headers: { Accept: "application/json" }
})