2

我使用 rails-api gem 创建了一个 API,并且我有一个基于 angular 的客户端应用程序,我在其中使用 ng-resource。

我确实认为我发送到我的 API 的请求应该更像 {post=>{"kind"=>"GGG"}} 而不是 {"kind"=>"GGG"} 我必须找到一种方法我的 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 回答