【问题标题】:Grape API : Return Location header after a creationGrape API:创建后返回 Location 标头
【发布时间】:2017-11-17 23:34:51
【问题描述】:

POST 请求应创建资源并返回指向已创建资源的“Location”标头。

我正在使用带有 Rails 的葡萄 API,并问自己返回创建的资源 URI 的最佳方式是什么。 葡萄是否提供了一种无需手动设置即可获取资源 URI 的方法?

resource :blup do
  post '/' do
    blup = Blup.create(first_name: 'Jamie')
    if blup.present?
      header 'Location', 'HERE blup URI'
    end
  end
end

【问题讨论】:

  • 试试 Rails.application.routes.url_helpers.blup_url blup.id

标签: ruby-on-rails grape-api


【解决方案1】:

目前我还没有找到比这更好的东西:

header 'Location', "#{request.url}/#{blup.id}"

但仅当 request.url 是资源根 URI 时才有效。 (例如在 POST 请求中)

【讨论】:

    【解决方案2】:

    虽然我不知道 Grape 在 Ruby on Rails API 中添加了什么,但我遇到了同样的问题,我找到了答案 here。 要在创建后在标题中给出位置,您可以添加:

    render location: specific_thing_i_am_looking_for_url(@thing)

    你可以通过运行找到 specific_thing_i_am_looking_for_url

    rake routes
    

    【讨论】:

      猜你喜欢
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      相关资源
      最近更新 更多