当我运行 Phoenix 框架测试时,出现此错误:
** (Phoenix.NotAcceptableError) no supported media type in accept header.
Expected one of ["html"] but got the following formats:
* "application/json" with extensions: ["json"]
To accept custom formats, register them under the :mime library
in your config/config.exs file:
config :mime, :types, %{
"application/xml" => ["xml"]
}
And then run `mix deps.clean --build mime` to force it to be recompiled.
即使我将此行添加到我的 config.exs
中,我仍然收到错误:
config :mime, :types, %{
"application/json" => ["json"]
}
我做错了什么?
最佳答案
在 router.ex
文件的顶部,您将有类似这样的内容,它定义了要使用的路由的管道:
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {FirehoseWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
然后,您将拥有使用这些管道并定义路由的范围:
scope "/", AppWeb do
pipe_through :browser
get "/", PageController, :index
end
上面的范围通过 :browser
进行管道传输,因此它只接受 html。如果您有单独的仅 JSON 路由“/api/foo”,那么您需要为其通过 :api
管道定义另一个作用域,如下所示:
scope "/api", AppWeb do
pipe_through :api
resources "/foo", FooController
end
如果您希望使用相同的路由来处理 HTML 和 JSON,则将管道中的第一个插件更改为: plug :accepts, ["html", "json"]
关于elixir - Phoenix .NotAcceptableError : no supported media type in accept header,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69933690/