Rails API 葡萄 |不支持内容类型

发布于 2025-01-12 16:08:02 字数 887 浏览 4 评论 0原文

module API
  class Root < Grape::API
    prefix 'api'

    content_type :json, 'application/json'
    format :json
    default_format :json

    rescue_from Grape::Exceptions::ValidationErrors do |e|
      error!({ error: [{ msg: 'card's information is incorrect' }] }, 400)
    end

    rescue_from :all

    mount API::Ver1::Poker
  end
end

这是我的 API 的根。 如果我请求 JSON 格式的内容,此 API 将返回正确的值。 但是,如果我请求其他格式(例如文本或 XML)的内容,则此 API 会返回如下所示。

{
    "error": "The provided content-type 'text/plain' is not supported."
}

或者

{
    "error": "The provided content-type 'application/xml' is not supported."
}

我想显示错误消息“卡片信息不正确”。

为什么下面的验证码不起作用?

rescue_from Grape::Exceptions::ValidationErrors do |e|
    error!({ error: [{ msg: 'card's information is incorrect' }] }, 400)
end
module API
  class Root < Grape::API
    prefix 'api'

    content_type :json, 'application/json'
    format :json
    default_format :json

    rescue_from Grape::Exceptions::ValidationErrors do |e|
      error!({ error: [{ msg: 'card's information is incorrect' }] }, 400)
    end

    rescue_from :all

    mount API::Ver1::Poker
  end
end

This is my API's root.
If I request something in JSON format, this API returns correct value.
However, if I request something in other formats such as Text or XML, this API returns like below.

{
    "error": "The provided content-type 'text/plain' is not supported."
}

or

{
    "error": "The provided content-type 'application/xml' is not supported."
}

I want to show error message 'cards information is incorrect'.

Why does not the following validation code work?

rescue_from Grape::Exceptions::ValidationErrors do |e|
    error!({ error: [{ msg: 'card's information is incorrect' }] }, 400)
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

喜爱皱眉﹌ 2025-01-19 16:08:03

因为您将 content-type 设置为 json,所以它不会接受任何其他 content-type

如果您希望支持所有 content-types

  • 请删除 content type:json,'application/json

  • 添加您想要支持的所有“内容类型”。
    content_type :json, 'application/json'
    内容类型:xml,'应用程序/xml'
    内容类型:txt,'文本/纯文本'
    

详细了解 grape API 格式

Because you set the content-type to json, so it won't accept any other content-type.

If you wish to support all content-types

  • either remvoe content type:json,'application/json line

OR

  • add all of the 'content-types' you want to support.
    content_type :json, 'application/json'
    content_type :xml, 'application/xml'
    content_type :txt, 'text/plain'
    

Read more about grape API formats

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文