Home > Software engineering >  Using Rails Controllers to make a web request and then display data
Using Rails Controllers to make a web request and then display data

Time:12-02

I have a rails controller that is making a web request, I would like to display the response body and status code inside of a view without saving the data to a model. I've tried using partials and instance variables but I've gotten no luck.

Here is what I have so far:

def create
    uri = URI.parse "https://#{login_params[:ip]}"
    http = Net::HTTP.new uri.host, uri.port

    http.use_ssl = true if uri.scheme == 'https' # Use SSL, Should probably be default
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE

    req = Net::HTTP::Post.new(uri.request_uri, headers)
    req.basic_auth login_params[:username].to_s, login_params[:password].to_s # Base64 encode username:password


    res = http.request(req, req_body) # make request

    body = Hash.from_xml(res.body)
    if res.code == 200
      redirect_to :show
    end 
end

Am I just better of making the request with Stimulus JS and appending the data to the screen?

CodePudding user response:

your issue here is you don't assign the value of your request to an instance variable for example you could do that:

def create
    uri = URI.parse "https://#{login_params[:ip]}"
    http = Net::HTTP.new uri.host, uri.port

    http.use_ssl = true if uri.scheme == 'https' # Use SSL, Should probably be default
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE

    req = Net::HTTP::Post.new(uri.request_uri, headers)
    req.basic_auth login_params[:username].to_s, login_params[:password].to_s # Base64 encode username:password


    res = http.request(req, req_body) # make request

    @body = Hash.from_xml(res.body)
    @code = res.code

    if res.code == 200
      redirect_to :show
    end 
end

then access it from the view like that:

<%= @body %>
<%= @code %>

CodePudding user response:

  1. Save the response into an instance variable
  2. render to the next action
  3. Add this to the view:
<% if @resp %> 
  <%= @resp.body %> 
<% end %>
  • Related