新手问题 net/http 的 post 传值问题

smallbottle · 2014年09月30日 · 最后由 smallbottle 回复于 2014年10月08日 · 2904 次阅读

用 net/http 库的 post 方法传值老是不成功,于是用 rails 写了个测试程序。

用 rails4,写了个表单,传值进去,然后在另一个页面显示。

表单:

<%= form_for :aa, url: "../example/index" do |f| %>
  <p>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :text %><br>
    <%= f.text_area :text %>
  </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>

controller 处理

def handle  
    @params = params["aa"]
    if @params['title'] == "1" and @params[:text] == "1"
        render "handle"
    else
        render "index"
    end
end

在网页上测试的好好的。

但是用 net/http 库,总会出错,如下 报错是 @params是 nil 值,undefined method `[]' for nil:NilClass。

但是确实又把参数读进去了,报错页面有如下信息。 Request Parameters: {"title"=>"1", "text"=>"2"}

我的代码:

require 'net/http'
require 'uri'

params = {:title=>'1',:text=>'2'}
uri = URI("http://localhost:3000/example/index")

req = Net::HTTP::Post.new(uri)
req.set_form_data(params)

res = Net::HTTP.start(uri.hostname, uri.port) do |http|
  http.request(req)
end

File.open('a.html','w') do |f|
    f.write res.body
end

请问各位大侠,这是什么问题啊

rails 自己的页面 post 的时候会带上

<meta content="authenticity_token" name="csrf-param" />
<meta content="CVoxuWEpAKTohDSBdYZ+Vulvi594cYPigayavQBvf/Y=" name="csrf-token" />
2 楼 已删除

#1 楼 @huobazi csrf 这个不是防止跨站请求伪造的吗?我用了 config.action_controller.allow_forgery_protection = false,关掉了它

#4 楼 @smallbottle 你自己 post 的代码里 params 里没有 aa controller 里 params 却有 aa

#1 楼 @huobazi aa 是表单的名字 form_for :aa

需要 登录 后方可回复, 如果你还没有账号请 注册新账号