繁体   English   中英

如何将JSON数据发布到我的Rails应用程序?

[英]how to post JSON data to my rails app?

我是新手。 我想通过Android应用程序使用我的其余API。 所以我想测试我的控制器是否处理POST请求。 我正在使用Chrome的高级REST客户端发出POST请求。

错误

错误的请求400-休息客户端(Chrome)

更新1:日志输出:

在2015年4月17日00:51:09 +0530为127.0.0.1启动POST“ / android”,解析请求参数时发生错误。 内容:

{tablet_id:1,脉冲:2,pulse_timestamp: 'NOW()'}

ActionDispatch :: ParamsParser :: ParseError(795:'{tablet_id:1,pulse:2,pulse_timestamp:'NOW()'}'处的意外令牌):

我的rails控制器:

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

查看滑轨布线指南 特别是在定义为控制器创建的HTTP动词类型的部分。 默认情况下,唯一的POST:create 但是,您可以通过更改路由来编辑路由,以显式允许您自定义API的POST。

也许这会有所帮助:

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

但是,当然,服务器日志输出将非常有帮助。

谢谢你们,经过很多努力后,它才能正常工作。 问题出在我的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请求(因为我正在使用chrome-addon发出POST请求)

我的json格式应该是:

{
    "pulse_feedback": {
        "tablet_id": "1",
        "pulse": "2",
        "pulse_timestamp": "NOW()"
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM