【问题标题】:dynamic urls in rails paramsrails 参数中的动态 url
【发布时间】:2017-04-29 13:02:32
【问题描述】:

我正在练习在 Rails 中制作 API。该 api 目前只有一个端点通过 get 请求接收 url。我的路线是:

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
    namespace :api, defaults: { format: :json } do
      namespace :v1 do # resources :orders
        get "*link" => "application#parse_link"
      end
    end
end

我的应用程序控制器代码:

require 'open-uri'

class Api::V1::ApplicationController < ActionController::Base
    respond_to :json
  # protect_from_forgery with: :exception

  def parse_link

        begin

            url = URI.parse(params[:link])
            doc = Nokogiri::HTML(open(url).read)

        rescue
            redirect_to 'http://localhost:3000/'
        end

  end
end

当我发送这样的网址时:

http://localhost:3000/api/v1/http://stackoverflow.com/questions/41138538/dynamic-urls-in-rails-params

效果很好

但以下类型的网址不起作用:

http://localhost:3000/api/v1/http://stackoverflow.com/

在这种情况下,它会拆分链接并给我这些参数

<ActionController::Parameters {"link"=>"http:/stackoverflow", "format"=>"com"} permitted: true>

如您所见,它将给定的 url 拆分并将其一半保存在链接参数中,并将“.com”部分保存在格式参数中。

谢谢

【问题讨论】:

  • url-escape 参数中的特殊字符:http://localhost:3000/api/v1/http%3A%2F%2Fstackoverflow.com%2F。如果这还不够,也请转义点。
  • 但是编码会在params上完成......我得到的Param已经被分割......它不是一个完整的url
  • 不,在发送请求之前对其进行编码。在 api 客户端中。当然不是 api 服务器。
  • 谢谢,但奥斯卡拉斯卡的回答有效。非常感谢
  • 但是为什么呢?如果您想创建一个带有 url 参数的方法,您可以对其进行 URI 编码并将其传递到查询字符串中。您正在创建的只是一个非常贪婪的包罗万象,将掩盖 404 错误。

标签: ruby-on-rails ruby api


【解决方案1】:

尝试将defaults 更改为constraints

Rails.application.routes.draw do
    namespace :api, constraints: { format: :json } do
      namespace :v1 do # resources :orders
        get "*link" => "application#parse_link"
      end
    end
end

注意:它会限制格式为 json,而不只是设置为默认。 Rails 将 URL 末尾的 .com 视为响应类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 2015-02-16
    • 1970-01-01
    • 2020-01-02
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多