我有一个Android应用程序,可以拍照并发送到Ruby on Rails上的RESTful API构建。当我从应用程序进行身份验证后上传图像时,发生 422 无法处理的实体错误。我使用载波宝石来处理图像。 这是我的 User_controller.rb 文件
class UsersController < ApplicationController
skip_before_action :authorize_request, only: :create
#skip_before_action :verify_auth_token
# POST /signup
# return authenticated token upon signup
def create
user = User.create!(user_params)
auth_token = AuthenticateUser.new(user.email, user.password).call
response = { message: Message.account_created, auth_token: auth_token }
json_response(response, :created)
end
def index
json_response(@current_user)
end
private
def user_params
params.permit(
:name,
:email,
:password,
:password_confirmation,
)
end
end
images_controller.rb 文件
class ImagesController < ApplicationController
before_action :set_user
before_action :set_user_image, only: [:show, :update, :destroy, :create]
def index
json_response(@current_user.images)
end
def show
json_response(@image)
end
def create
@current_user.images.create(image_params)
json_response(@current_user, :user_id)
end
private
def image_params
params.permit(:photo)
end
def set_user
@current_user = User.find(params[:user_id])
end
def set_user_image
@image = @current_user.images.find_by!(id: params[:id]) if @current_user
end
end
这是我的模型文件。 用户.rb
# app/models/user.rb
class User < ApplicationRecord
mount_uploader :photo, PhotoUploader
# encrypt password
has_secure_password
has_many :images, foreign_key: :user_id
# Validations
validates_presence_of :name, :email, :password_digest
end
图片.rb
class Image < ApplicationRecord
mount_uploader :photo, PhotoUploader
belongs_to :user
end
路线.rb
Rails.application.routes.draw do
resources :users do
resources :images
end
post 'auth/login', to: 'authentication#authenticate'
post 'signup', to: 'users#create'
post 'images', to: 'images#create'
end
错误日志:
Started POST "/images" for 203.159.41.110 at 2017-07-03 21:44:56 +0700
Processing by ImagesController#create as HTML
Parameters: {"photo"=>#<ActionDispatch::Http::UploadedFile:0x005615c5a900e8 @tempfile=#<Tempfile:/tmp/RackMultipart20170703-29818-3gozwl.jpg>, @original_filename="IMG_20170703_202628.jpg", @content_type="application/octet-stream", @headers="Content-Disposition: form-data; name="photo"; filename="IMG_20170703_202628.jpg"rnContent-Type: application/octet-streamrnContent-Transfer-Encoding: binaryrn">, "auth_token"=>"token"}
Completed 422 Unprocessable Entity in 2ms (Views: 1.2ms | ActiveRecord: 0.0ms)
经过大量研究,我发现身份验证令牌没有被处理。将身份验证令牌作为标头发送解决了httppost.setHeader("Authorization:", token);
的问题
我想你可能错过了处理authenticity_token,默认情况下每个 POST 请求都需要它。
您可以禁用它,但它会暴露您的 api 跨站点请求伪造 (CSRF( 攻击。
class UsersController < ApplicationController
protect_from_forgery unless: -> { request.format.json? }
end
还将移动设备中的请求类型更改为应用程序/JSON
参考 : http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html#M000491