2015-04-16 49 views
1

我是新來的鐵軌。我想用android應用程序來使用我的rest API。所以我想測試我的控制器是否處理POST請求。我正在使用高級REST客戶端進行chrome發出POST請求。如何將JSON數據發佈到我的Rails應用程序?

錯誤

爲請求400 - 其餘客戶端(鉻)

更新1: 日誌輸出:

開始POST 「/機器人」 爲127.0.0.1在2015 - 04-17 00:51:09 +0530 解析請求參數時發生錯誤。 內容:

{tablet_id:1,脈衝:2,pulse_timestamp: 'NOW()'}

ActionDispatch :: ParamsParser :: ParseError(795:1,脈衝:在「{tablet_id意外的標記2 ,pulse_timestamp: 'NOW()'}「):

我的軌控制器:

class Android::PulseFeedbacksController < ApplicationController 
    before_action :set_pulse_feedback, only: [:show, :edit, :update,:destroy] 
    respond_to json 
    # GET /pulse_feedbacks 
    # GET /pulse_feedbacks.json 
    def index 
    @pulse_feedbacks = PulseFeedback.all 
    respond_to do |format| 
     format.json { render json: @pulse_feedbacks } 
     format.xml { render xml: @pulse_feedbacks } 
    end 
    end 

    def create 
    @pulse_feedback = PulseFeedback.new(pulse_feedback_params) 

    respond_to do |format| 
     if @pulse_feedback.save 
     format.html { redirect_to @pulse_feedback, notice: 'Pulse feedback was successfully created.' } 
     format.json { render :show, status: :created, location: @pulse_feedback } 
     else 
     format.html { render :new } 
     format.json { render json: @pulse_feedback.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_pulse_feedback 
     @pulse_feedback = PulseFeedback.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def pulse_feedback_params 
     params[:pulse_feedback] 
    end 
end 
+0

您的服務器日誌將有更多的信息,告訴您到底發生了什麼(以及可能發生了什麼問題) –

+0

@JanHøjriisDragsbaek服務器錯誤是:解析請求參數時發生錯誤。 內容: {pulse_feedback:{tablet_id:1,pulse:2,pulse_timestamp:'NOW()'}}我發送json數據格式錯誤嗎? –

+0

您應該更新問題以包含日誌輸出。 –

回答

0

也許這將有助於:

def pulse_feedback_params 
    params.require(:pulse_feedback).permit! 
end 

但當然服務器日誌輸出將是非常有用的。

1

查看rails routing guides。特別是在它定義爲控制器創建的HTTP動詞類型的部分。默認情況下,唯一的POST:create。但是你可以通過改變路由來編輯你的路由,以明確地允許你的自定義API的POST。

0

謝謝你們,很多頭破了之後,它工作。 問題出在我的application_controller.rb和我的json格式上面。

我不得不註釋此行

before_action :authenticate_user! 

在我application_controller.rb文件

class ApplicationController < ActionController::Base 
     respond_to :html, :json 

     # Prevent CSRF attacks by raising an exception. 
     # For APIs, you may want to use :null_session instead. 
     protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' } 
     #before_action :authenticate_user! 
end 

它不接受來自未授權客戶POST請求(因爲我是用鉻附加到使POST請求)

而我的json格式應該是:

{ 
    "pulse_feedback": { 
     "tablet_id": "1", 
     "pulse": "2", 
     "pulse_timestamp": "NOW()" 
    } 
} 
相關問題