Phoenix.NotAcceptableError: no supported media type in accept header

Phoenix.NotAcceptableError: no supported media type in accept header

当我 运行 我的 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。如果你有单独的路由“/api/foo”,那是 JSON-only,那么你会想要通过 :api 为它定义另一个范围,如下所示:

    scope "/api", AppWeb do
    pipe_through :api

    resources "/foo", FooController
  end

如果您希望同一路由同时处理 HTML 和 JSON,则将管道中的第一个插件更改为:plug :accepts, ["html", "json"]