Agung Kessawa
Agung Kessawa

Reputation: 563

http::request to internal link return nil

I'm trying to call internal action using http::request, but it always giving nil in it's response.body.

Here is the code in the view file,

<%= @res.body.html_safe %>

Here is the code in controller

def index2
    require "net/http"
    require "uri"

    url = URI.parse("http://localhost:3000/")

    req = Net::HTTP::Post.new(url.request_uri)
    req.set_form_data({'email'=>'[email protected]', 'pass'=>'zeas2345'})
    http = Net::HTTP.new(url.host, url.port)

    @res = http.request(req)
end

and the result is

NoMethodError in Main#index2

Showing D:/WORK/ERP_BALIYONI/app/views/main/index2.html.erb where line #5 raised:
undefined method `body' for nil:NilClass

2:   
3: %>
4: 
5: <%= @res.body.html_safe %>

I'm quite confused because when I change the url into

url = URI.parse("http://localhost3000.org/")

it works. Can you help me find the problem?

Upvotes: 1

Views: 577

Answers (1)

Rajarshi Das
Rajarshi Das

Reputation: 12330

Your response get nil

@res = http.request(req) here @res is nil so when you try @res.body it is throwing undefined method body for nil:NilClass

you can ty

in index.html.erb:

<%= @res.try(:body).try(:html_safe) %>

Upvotes: 1

Related Questions