【问题标题】:Phoenix.NotAcceptableError: no supported media type in accept headerPhoenix.NotAcceptableError:接受标头中不支持媒体类型
【发布时间】:2021-12-24 06:10:27
【问题描述】:

当我运行我的 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"]
}

我做错了什么?

【问题讨论】:

  • 您在路由器管道的某处有plug :accepts, ["json"] 吗? (见docs
  • 就是这样!我将路由放在 :browser 范围内,我应该将其更改为 :api 以接受 json。

标签: elixir phoenix-framework mime-types mime


【解决方案1】:

在您的 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"]

【讨论】:

    猜你喜欢
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2015-06-17
    • 2014-05-10
    相关资源
    最近更新 更多