簡體   English   中英

使用CURL for Rails App的POST請求

[英]POST request using CURL for Rails App

許多用戶已經問過這個問題,我已經嘗試了所有的解決方案,但是沒有一個解決過這個問題。例如:這個問題在這里通過終端curl json post請求到rails應用程序,但結果仍然相同。

我試圖通過運行此命令使用CURL通過終端POST數據:

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

關於上面的對話,讓我寫一個答案。

如果您在rails中看到一個表單,它將具有如下所述的行

<input name="authenticity_token" type="hidden" value="+wFCV3kv0X/WI0qb54BgYlDzi+Tp+6HIGM61a4O6gg0=">

現在,如果在ApplicationController你有這行protect_from_forgery那么它總是會期望authenticity_token ,如果它不可用,它將拋出你日志中提到的錯誤,因此我建議刪除該行,因為你不會將authenticity_token作為一個來自你api POST請求的param。

您的get請求工作正常的原因是因為rails不期望GET請求上的authenticity_token

現在,你說你刪除了protect_from_forgery但你得到了一個內部服務器錯誤,因為它與GETPOST請求無關,所以你必須處理它,但是你的rails應用程序出錯了。 所以解決這個錯誤,它應該工作得很好。 或者也可以在這里發布錯誤日志,這樣我可以幫助你。

編輯:解決您的內部服務器500錯誤

使用下面粘貼的日志,您還必須允許控制器中的屬性,就像@abhinay在代碼中提到的那樣。

希望有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM