【发布时间】:2015-01-08 10:59:25
【问题描述】:
很多用户都问过这个问题,我已经尝试了所有解决方案,但没有一个有效。例如:这个问题在这里curl json post request via terminal to a rails app,但结果仍然相同。
我正在尝试通过运行以下命令使用 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
并获得响应:
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
有这么多垃圾行,但我想这个响应足以理解可能是什么原因。这是完成错误http://pastebin.com/n342HeYL的链接
我可以使用命令成功地执行 GET 请求:
curl -i 'http://localhost:3000/api/v1/requests' -H 'Authorization: Token token'="952aa4598ec2cd87c8b69056616a00af"
回复:
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
所以,我不知道 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
【问题讨论】:
-
你能从你的应用程序控制器评论这行
protect_from_forgery并检查它是否工作吗?从您的日志中,我认为这是导致问题的原因,因为请求是POST,这通常是rails 的表单提交。检查并告诉我 -
@PamioSolanky 其“HTTP/1.1 500 内部服务器错误”
-
调试它并解决错误,因为它是服务器端的,或者返回跟踪以查看错误是什么:) 同样在您的日志中,您可以看到这些行
ActionController::InvalidAuthenticityTokenactionpack (4.1.5) lib/action_controller/metal/request_forgery_protection.rb:176:inhandle_unverified_request' ` 这意味着,对于 rails 而言,每当提交表单时,rails 通常会从 rails 生成的令牌检查其真实性。因此,如果没有令牌或令牌被篡改,那么 Rails 会将其视为攻击。因此它不会处理请求。所以清除错误 -
抱歉,我不明白您要建议什么。正如您所看到的,使用相同的身份验证令牌我可以进行 GET 请求。
标签: ruby ruby-on-rails-4 curl