Ruby-on-rails 我应该如何格式化对我的 rails 应用程序的 JSON POST 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18690196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:40:35  来源:igfitidea点击:

How should I format a JSON POST request to my rails app?

ruby-on-railsjsonrest

提问by drewwyatt

My Rails app has a player class that works perfectly. Players can be created, deleted, and updated from my rails control panel without any issues.

我的 Rails 应用程序有一个完美运行的播放器类。可以从我的 rails 控制面板创建、删除和更新播放器,没有任何问题。

I would like a remote counterpart to be able to join in the fun by creating players using a JSON request. Following the advice of the auto generated Rails comments above my create method : # POST /players.jsonI have started sending requests to localhost:3000/players.json

我希望远程对应方能够通过使用 JSON 请求创建玩家来参与其中。按照我的创建方法上方自动生成的 Rails 注释的建议:# POST /players.json我已经开始向localhost:3000/players.json

The JSON

JSON

{
    "player": {
    "name": "test",
    "room_id": 0,
    "skin_id": 1,
    "head_id": 2,
    "torso_id": 3,
    "legs_id": 4,
    "x_position": 5,
    "y_position": 6,
    "direction": 7,
    "action": "",
    "gender": "f"
    }
}

However, I am running into this error message:

但是,我遇到了此错误消息:

ActionController::ParameterMissing in PlayersController#create param not found: player

ActionController::ParameterMissing in PlayersController#create param not found: player

So I guess my question is: How should I structure the JSON I am sending?

所以我想我的问题是:我应该如何构建我发送的 JSON?

Additional info:

附加信息:

  • Ruby Version: 2.0
  • Rails Version: 4.0
  • I have tried sending my requests using Postman
  • 红宝石版本:2.0
  • 导轨版本:4.0
  • 我曾尝试使用Postman发送我的请求

Update - Player Params

更新 - 玩家参数

Here is the player params method from my controller (as requested):

这是我的控制器中的 player params 方法(根据要求):

def player_params
    params.require(:player).permit(:name, :room_id, :skin_id, :head_id, :torso_id, :legs_id, :x_position, :y_position, :direction, :action, :gender)
end

Update 2 - Player controller

更新 2 - 播放器控制器

class PlayersController < ApplicationController
  before_action :set_player, only: [:show, :edit, :update, :destroy]
  skip_before_filter :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }

  # GET /players
  # GET /players.json
  def index
    @players = Player.all
  end

  # GET /players/1
  # GET /players/1.json
  def show
  end

  # GET /players/new
  def new
    @player = Player.new
  end

  # GET /players/1/edit
  def edit
    @rooms = Room.all.map { |room| [room.name, room.id] }
  end

  # POST /players
  # POST /players.json
  def create
    @player = Player.new(player_params)

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

  # PATCH/PUT /players/1
  # PATCH/PUT /players/1.json
  def update
    respond_to do |format|
      if @player.update(player_params)
        format.html { redirect_to @player, notice: 'Player was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @player.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /players/1
  # DELETE /players/1.json
  def destroy
    @player.destroy
    respond_to do |format|
      format.html { redirect_to players_url }
      format.json { head :no_content }
    end
  end

  def manage_furni
    @player = Player.find(params[:id])
    @furni = Furni.all
  end

  def add_furni
    player = Player.find(params[:id])
    player.furnis << Furni.find(params[:furni])
    redirect_to manage_furni_path(player)
  end

  def remove_furni
    player = Player.find(params[:id])
    item = InventoryItem.find(params[:item])
    player.inventory_items.delete(item)
    redirect_to manage_furni_path(player)
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def player_params
      params.require(:player).permit(:name, :room_id, :skin_id, :head_id, :torso_id, :legs_id, :x_position, :y_position, :direction, :action, :gender)
    end
end

Update 3: logs

更新 3:日志

(
    "Processing by PlayersController#create as JSON",
    "Completed 400 Bad Request in 31ms",
    "ActionController::ParameterMissing (param not found: player):",
    "app/controllers/players_controller.rb:103:in `player_params'",
    "app/controllers/players_controller.rb:40:in `create'",
    "Rendered /Users/drewwyatt/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.5ms)",
    "Rendered /Users/drewwyatt/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (0.9ms)",
    "Rendered /Users/drewwyatt/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.8ms)",
    "Rendered /Users/drewwyatt/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (16.3ms)"
){
}

回答by Michael Osl

First of all, I think your data format is ok and is not the problem here. When I ran exactly into the same problem it was because I did not send the Content-Type: application/jsonheader along with my request.

首先,我认为您的数据格式没问题,不是这里的问题。当我遇到完全相同的问题时,那是因为我没有将Content-Type: application/json标头与我的请求一起发送。

In Postman, you can select the 'raw' data format and then 'JSON (application/json)' to include this header. In my case it looks like this:

在 Postman 中,您可以选择“原始”数据格式,然后选择“JSON (application/json)”以包含此标头。就我而言,它看起来像这样:

Screenshot of sending a JSON request to a rails application in Postman

在 Postman 中向 Rails 应用程序发送 JSON 请求的屏幕截图

Alternatively, you can also try it with curl(source):

或者,您也可以尝试使用curl( source):

curl -X POST -H "Content-Type: application/json" -d '{"player": {"name": "test","room_id": 0,"skin_id": 1,"head_id": 2,"torso_id": 3,"legs_id": 4,"x_position": 5,"y_position": 6,"direction": 7,"action": "","gender": "f"}}' localhost:3000/players.json

curl -X POST -H "Content-Type: application/json" -d '{"player": {"name": "test","room_id": 0,"skin_id": 1,"head_id": 2,"torso_id": 3,"legs_id": 4,"x_position": 5,"y_position": 6,"direction": 7,"action": "","gender": "f"}}' localhost:3000/players.json

If you omit the -H "Content-Type: application/json", then you will receive a 400 response with the "param not found" error, if you include it it should work.

如果省略-H "Content-Type: application/json",那么您将收到带有“param not found”错误的 400 响应,如果包含它,它应该可以工作。

回答by jesal

If you are trying this:

如果你正在尝试这个:

via Postman - Under form-data tab, you need to have the vars as :

通过邮递员 - 在表单数据选项卡下,您需要将变量设置为:

player[name]
player[room_id]
.
.

via jQuery:

通过jQuery:

$.ajax({ url: 'url', type: 'post', data: { player: { name: 'Test', room_id: '0' } } })