2

rails-api gem を使用して API を作成し、ng-resource を使用する angular ベースのクライアント アプリを作成しました。

API に送信するリクエストは、{post=>{"kind"=>"GGG"}} のようにする必要があり、{"kind"=>"GGG"} ではなく、I have to find a way for私のAPIは、今送信したリクエストを処理します。今のところ、400 個の Bad Request エラーが発生しており、修正方法がわかりません。

  • これが私のレールコントローラーです:

    class PostsController < ApplicationController
      # GET /posts
      # GET /posts.json
      skip_before_filter :verify_authenticity_token, :only => [:update, :create]
    
      def index
        @posts = Post.all
    
        render json: @posts
      end
    
      # GET /posts/1
      # GET /posts/1.json
      def show
        @post = Post.find(params[:id])
    
        render json: @post
      end
    
      # POST /posts
      # POST /posts.json
      def create
        @post = Post.new(post_params)
    
        if @post.save
          render json: @post, status: :created, location: @post
        else
          render json: @post.errors, status: :unprocessable_entity
        end
      end
    
      # PATCH/PUT /posts/1
      # PATCH/PUT /posts/1.json
      def update
        @post = Post.find(params[:id])
    
        if @post.update(params[:post])
          head :no_content
        else
          render json: @post.errors, status: :unprocessable_entity
        end
      end
    
      # DELETE /posts/1
      # DELETE /posts/1.json
      def destroy
        @post = Post.find(params[:id])
        @post.destroy
    
        head :no_content
      end
    
      private
      def post_params
        params.require(:post).permit(:post, :kind)
      end
    end
    
  • これが私の角度コントローラーです:

         $scope.postData = {};
         $scope.newPost = function() {
          console.log($scope.postData);
              var post = new Post($scope.postData);
              post.$save($scope.postData);
          }
    
  • ここに私の角度工場があります:

       .factory('Post', function($resource) {
          return $resource('http://localhost:3000/posts');
       })
    
  • 私のログには次のものがあります:

     Started POST "/posts?kind=GGG" for 127.0.0.1 at 2014-05-26 18:21:21 +0200
     Processing by PostsController#create as HTML
       Parameters: {"kind"=>"GGG"}
     Completed 400 Bad Request in 2ms
    
     ActionController::ParameterMissing (param is missing or the value is empty: post):
       app/controllers/posts_controller.rb:55:in `post_params'
       app/controllers/posts_controller.rb:23:in `create'
    

-

4

1 に答える 1

4

次のコードを変更します。

def post_params
  params.require(:post).permit(:post, :kind)
end

することが:

def post_params
  params.permit(:post, :kind)
end

そして、あなたの問題は修正されます。

于 2014-08-26T06:15:52.833 に答える