Ruby获取GET请求数据

时间:2020-02-19 02:58:10

标签: ruby axios ruby-on-rails-5

我正在制作API端点,但无法获取请求的正文。这是我所拥有的:

在路线中,我在名称空间中设置了一个端点:

namespace :api, :defaults => {:format => :json}  do
    resources :mainview do
        collection do
            get 'data'
        end
    end

在前端,我调用/ api / mainview / data端点,并将其传递给json内的日期:

axios.get('/api/mainview/data', {"start_date":"2020-01-01"})
    .then(response => {
      console.log(response)
    })
    .catch(error => {
      console.log("We are getting this error:")
      console.log(error)
    });

然后,在我的/api/mainview_controller.rb文件中,我得到了

module Api
    class MainviewController < AuthenticatedController
        def data
            puts "We are in the data function"
            #I want to print the body ({"start_date":"2020-01-01"}) of the request here 
        end
    end
end

因此,在这种情况下,我的API调用似乎可以正常工作,因为We are in the data function确实已打印到终端上。但是,我不知道如何从请求中获取正文或数据。如果是邮寄请求,我知道我可以使用request.raw_post,但不知道该如何使用GET请求。我在网上找到的大多数答案都在PHP中,所以任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

您必须通过Rails呈现响应,并且必须在Rails打包并将其发送回之前实际在响应中构建输出。

def data
  render json: { 
      start_date: params[:start_date] 
    }
end