elixir - Phoenix .NotAcceptableError : no supported media type in accept header

标签 elixir phoenix-framework mime-types mime

当我运行 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/

相关文章:

phoenix-framework - Phoenix : Running mix ecto. 创建错误编译牧场依赖

java - 如何检测 mime 类型是否用于可执行文件?

c++ - libavformat:在 C++ 中获取格式 Mime 类型

elixir - 这些不同的函数定义有何优缺点?

macros - Elixir:在定义它的同一模块的主体中​​使用宏

elixir - 如何对文本进行模式匹配?

erlang - 在 Exometer 中发送 Datadog 标签

sockets - 我无法获得通过在不老长寿药, Phoenix 中的存在而加入 channel 的所有用户的列表

elixir - 在 Elixir 中使用 Erlang 库

python - 使用Python将文件上传到S3(保留原始文件夹结构)并具有正确的MIME类型