簡體   English   中英

Rails參數中的動態網址

[英]dynamic urls in rails params

我正在練習在Rails中制作API。 該api目前只有一個端點,該端點通過get請求接收網址。 我的路線是:

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”部分保存在格式參數中。

謝謝

嘗試將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視為響應類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM