Ruby获取GET请求数据

问题描述 投票:1回答:1

我正在制作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中,所以任何帮助都将非常有用!

ruby axios ruby-on-rails-5
1个回答
0
投票

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

def data
  render json: { 
      start_date: params[:start_date] 
    }
end
© www.soinside.com 2019 - 2024. All rights reserved.