Ily*_*lya 0 json elixir phoenix-framework
当路由不匹配时,我尝试发送 json。从error_view.ex,我认为错误首先出现:
def template_not_found(_template, assigns) do
render "404.html", assigns
end
Run Code Online (Sandbox Code Playgroud)
但如果我将其更改为:
def template_not_found(_template, assigns) do
%{message: "custom error"}
end
Run Code Online (Sandbox Code Playgroud)
它实际上并不发送 json ,而是返回 me no function clause matching in Phoenix.Template.HTML.encode_to_iodata!/1。我相信这是因为它需要发送一些 html。可以改成发送json吗?
我的路由器:
defmodule AppWeb.Router do
use AppWeb, :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 "/", AppWeb do
pipe_through :browser # Use the default browser stack
get "/", PageController, :index
end
scope "/api", AppWeb do
pipe_through :api
end
end
Run Code Online (Sandbox Code Playgroud)
在config/config.exs更新render_error选项中:
config :my_app, MyApp.Endpoint,
render_errors: [view: MyApp.ErrorView,
format: "json",
accepts: ~w(json)]
Run Code Online (Sandbox Code Playgroud)