Ruby on rails 如何将JSON数据发布到我的rails应用程序?
我是rails的新手。我想用android应用程序使用RESTAPI。所以我想测试我的控制器是否处理POST请求。我正在使用用于chrome的高级REST客户端发出POST请求 错误 错误请求400-rest客户端(chrome) 更新1: 日志输出: 于2015年4月17日00:51:09+0530开始发布127.0.0.1版的“/android” 分析请求参数时出错。 内容: {tablet_id:1,pulse:2,pulse_时间戳:'NOW()'} ActionDispatch::ParamsParser::ParseError(795:位于“{tablet_id:1,pulse:2,pulse_timestamp:'NOW()'}”的意外标记): 我的rails控制器:Ruby on rails 如何将JSON数据发布到我的rails应用程序?,ruby-on-rails,ruby,json,rest,Ruby On Rails,Ruby,Json,Rest,我是rails的新手。我想用android应用程序使用RESTAPI。所以我想测试我的控制器是否处理POST请求。我正在使用用于chrome的高级REST客户端发出POST请求 错误 错误请求400-rest客户端(chrome) 更新1: 日志输出: 于2015年4月17日00:51:09+0530开始发布127.0.0.1版的“/android” 分析请求参数时出错。 内容: {tablet_id:1,pulse:2,pulse_时间戳:'NOW()'} ActionDispatch::Pa
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
class Android::PulseFeedbackController
也许这会有帮助:
def pulse_feedback_params
params.require(:pulse_feedback).permit!
end
当然,服务器日志输出将非常有用。请查看。特别是在定义为控制器创建的HTTP谓词类型的部分。默认情况下,唯一的
POST
是:create
。但您可以通过更改路由来编辑路由,以明确允许发布您自己的自定义API 谢谢你们,在经历了一番头破血流之后,它开始工作了。
问题在于我的应用程序_controller.rb和上面的json格式
我不得不评论这句话
before_action :authenticate_user!
在我的应用程序\u 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
您的服务器日志将包含更多信息,准确地告诉您发生了什么(以及可能的错误)@JanHøjriisDragsbaek服务器错误是:解析请求参数时出错。内容:{pulse_反馈:{tablet_id:1,pulse:2,pulse_时间戳:'NOW()'}}我是否以错误的格式发送json数据?您应该更新问题以包含日志输出。
{
"pulse_feedback": {
"tablet_id": "1",
"pulse": "2",
"pulse_timestamp": "NOW()"
}
}