【问题标题】:Curl command failing when send post request to rails app将发布请求发送到 Rails 应用程序时,Curl 命令失败
【发布时间】:2016-11-08 18:31:03
【问题描述】:

我有以下路线:

match '/curl_example' => 'people#curl_post_example', via: :post

在我的控制器中:

class PeopleController < ApplicationController
  before_action :set_person, only: [:show, :edit, :update, :destroy]
  skip_before_action :verify_authenticity_token, :only => [:curl_post_example]
...
  def curl_post_example
    Person.create(request.body.read)
    render plain: "Thanks for sending a POST request with cURL! Payload: #{request.body.read}"
  end
...

我正在尝试通过 curl 命令使用以下命令创建一个人...

curl -X POST -d "{"first_name"=>"mista", "last_name"=>"wintas"}" http://localhost:3000/curl_example

当我这样做时,我在控制台收到此错误...

Started POST "/curl_example" for ::1 at 2016-11-08 13:24:46 -0500
Processing by PeopleController#curl_post_example as */*
  Parameters: {"{first_name"=>">mista, last_name=>wintas}"}
Completed 500 Internal Server Error in 0ms (ActiveRecord: 0.0ms)



ArgumentError (When assigning attributes, you must pass a hash as an argument.):

对我来说看起来像一个哈希?我错过了什么?

【问题讨论】:

  • 尝试传递 Person.create(params) 而不是 Person.create(request.body.read)
  • 我使用参数得到错误ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):。如果我传入 person_params 我确实会得到更远的错误ActionController::ParameterMissing (param is missing or the value is empty: person): 此外,如果我传入curl -X POST -d ""person"=&gt;{"first_name"=&gt;"mista", "last_name"=&gt;"wintas"}" http://localhost:3000/curl_example 我会收到错误NoMethodError (undefined method permit' for ">{first_name=>mista, last_name=>wintas}" :String`

标签: ruby-on-rails curl


【解决方案1】:

你需要像这样传递参数:

 curl -d "person[first_name]=john" -d "person[last_name]=doe" 

来源:curl command line

然后,在您的控制器中:

private def person_params
  params.require(:person).permit(:first_name, :last_name)
end

并在Person.create... 中调用person_params 而不是params

【讨论】:

  • 使用上面的代码我得到错误ActionController::ParameterMissing (param is missing or the value is empty: person):
  • 你需要像这样传递参数curl -d "person[first_name]=john" -d "person[last_name]=doe" 来源:stackoverflow.com/questions/5826690/curl-command-line-post
  • 甜蜜。多谢,伙计。如果您想编辑上面的答案,我会接受。
猜你喜欢
  • 2019-07-06
  • 2011-08-05
  • 2019-08-08
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-19
相关资源
最近更新 更多