Abh*_*nay 5 ruby curl ruby-on-rails-4
这个问题已经被很多用户问到了,我已经尝试了所有解决方案,但都没有解决。例如:这个问题在这里通过终端向Rails应用程序卷曲json post请求,但结果仍然相同。
我正在尝试通过运行以下命令,使用CURL通过终端发布数据:
curl -i -H 'Authorization: Token token'="9asdadsasd87t8ddaghsd" -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"request":{"sender_mobile":"12331212","recipient_mobile":"121231231","location":"Bangalore"}}' http://localhost:3000/api/v1/requests
Run Code Online (Sandbox Code Playgroud)
和得到回应:
HTTP/1.1 422 Unprocessable Entity
Content-Type: text/html; charset=utf-8
Content-Length: 15450
X-Request-Id: f1025e69-9ff3-4bd1-9bd5-0679fbcc50bc
X-Runtime: 0.062784
Server: WEBrick/1.3.1 (Ruby/2.1.1/2014-02-24)
Date: Thu, 08 Jan 2015 10:35:45 GMT
Connection: Keep-Alive
Run Code Online (Sandbox Code Playgroud)
有这么多行的垃圾,但我想这个反应足以理解可能是什么原因。这里是完整错误的链接http://pastebin.com/n342HeYL
我可以使用以下命令成功执行GET请求:
curl -i 'http://localhost:3000/api/v1/requests' -H 'Authorization: Token token'="952aa4598ec2cd87c8b69056616a00af"
Run Code Online (Sandbox Code Playgroud)
响应:
HTTP/1.1 200 OK
X-Frame-Options: SAMEORIGIN
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Type: application/json; charset=utf-8
Etag: "b956523e0345d2bb466d39823195b600"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: 91d21235-246f-4557-a67a-92dca02b9cc1
X-Runtime: 0.011781
Server: WEBrick/1.3.1 (Ruby/2.1.1/2014-02-24)
Date: Thu, 08 Jan 2015 10:51:55 GMT
Content-Length: 486
Connection: Keep-Alive
Run Code Online (Sandbox Code Playgroud)
因此,我不知道POST请求出了什么问题。
这是我的request_controller.rb文件
module Api
module V1
class RequestsController < ApplicationController
# skip_before_action :verify_authenticity_token
before_filter :restrict_access
respond_to :json
def index
respond_with Request.all
end
def show
respond_with Request.find(params[:id])
end
def create
respond_with Request.create(params[:request])
end
def update
respond_with Request.update(params[:id], params[:request])
end
def destroy
respond_with Request.destroy(params[:id])
end
private
def restrict_access
authenticate_or_request_with_http_token do |token, options|
ApiKey.exists?(access_token: token)
end
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
针对上面的对话,我来写一个答案。
如果您在 Rails 中看到一个表格,它将有一条线,如下所述
<input name="authenticity_token" type="hidden" value="+wFCV3kv0X/WI0qb54BgYlDzi+Tp+6HIGM61a4O6gg0=">
Run Code Online (Sandbox Code Playgroud)
现在,如果ApplicationController你有这一行protect_from_forgery,那么它总是会期望authenticity_token,如果它不可用,它会抛出日志中提到的错误,因此我建议删除该行,因为你不会authenticity_token从 api 传递 an 作为参数POST要求。
您的 get 请求工作正常的原因是 Rails 不authenticity_token期望GET。
现在,您说您已删除,但出现了内部服务器错误,这必须由您处理,因为它与或protect_from_forgery无关GETPOST但它是您的 Rails 应用程序中的错误。因此,解决该错误,它应该可以正常工作。或者也可以在此处发布错误日志,以便我可以帮助您。
编辑:内部服务器 500 错误的解决方案
使用下面粘贴的日志,还需要允许控制器中的属性,就像代码中提到的 @abhinay 一样。
希望有帮助
| 归档时间: |
|
| 查看次数: |
1295 次 |
| 最近记录: |