如何在rails中访问Post方法请求的数据

时间:2015-12-11 12:49:38

标签: ruby-on-rails

尝试使用 POST 方法从某个API访问数据,但它返回我发送的实际params列表。这是我的代码,我不知道我是否做得对,我很乐意为你提供帮助。

这是我的控制器

  #Request access token from ExactApi
  params =  {
             "code" => "#{code}",
             "redirect_uri" => '/auth/exact/callback',
             "grant_type"   => "authorization_code",
             "client_id"   => "{CLIENT_ID}",
             "client_secret" => "CLIENT_SECRET"
           }
uri = URI.parse('https://start.exactonline.nl/api/oauth2/token')

#Encode the url into /x-www-form-urlencoded
uri.query = URI.encode_www_form(params)

#Transform http protocol into a secure protocol[https]
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE # You should use VERIFY_PEER in production

#Send the request to the ExactApi and return the received data
res  = Net::HTTP::Post.new(uri.request_uri)
res.set_form_data(params)
puts "Received:: "+ res.body.to_yaml

输出

code[CODE]&redirect_uri=%2Fauth%2Fexact%2Fcallback&grant_type=authorization_code&client_id=CLIENT_ID&client_secret=SECRET_ID

如何访问从API返回的实际数据?

2 个答案:

答案 0 :(得分:0)

您正在使用puts输出到服务器控制台。我混淆了输出的位置。您应该为自己设置一个与您的代码块所在的控制器操作同名的视图,例如,如果这是索引操作:

def index
  params= { your_hash_keys: "value" }
end

然后你应该在app / views / controller_name /里面有一个index.html.erb而不是puts "Received:: "+ res.body.to_yaml使用@debug = "Received:: "+ res.body.to_yaml并在你的视图中做一些输出就像<% = @ debug.inspect%>

或者,不建议在控制器中呈现内联:

render inline: "Received:: " + res.body.to_yaml

Layouts and Rendering with inline

您还应该重命名params变量,因为Rails将其用于传入参数。总而言之,我认为关于MVC的教程将是一个很好的起点。

答案 1 :(得分:0)

require "net/http"
require "uri"

uri = URI.parse('https://start.exactonline.nl/api/oauth2/token')
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE # You should use VERIFY_PEER in production
request.set_form_data({
     "code" => "#{code}",
     "redirect_uri" => '/auth/exact/callback',
     "grant_type"   => "authorization_code",
     "client_id"   => CLIENT_ID,
     "client_secret" => CLIENT_SECRET
})

response = http.request(request)

http://www.rubyinside.com/nethttp-cheat-sheet-2940.html

但是我会使用Omniauth而不是重新发明Oauth轮。很难做对。如果您找不到现成的提供商,那么创建自定义提供商非常简单:

require 'omniauth-oauth2'

module OmniAuth
  module Strategies
    class ExactOnline < OmniAuth::Strategies::OAuth2
      # change the class name and the :name option to match your application name
      option :name, :exactonile

      option :client_options, {
        :site => "https://start.exactonline.nl",
        :authorize_url => "/api/oauth2/token"
      }

      uid { raw_info["id"] }

      info do
        {
          :email => raw_info["email"]
          # and anything else you want to return to your API consumers
        }
      end

      def raw_info
        @raw_info ||= access_token.get('/api/v1/me.json').parsed
      end
    end
  end
end