rails4系のAPIに画像を送信したらタイトルのエラーが発生しました
SPAクライアントから画像データが送信されてAPIで画像を保存する感じです
こちらをそれぞれ作成し
config/initializers/bad_multipart_form_data_sanitizer.rb class BadMultipartFormDataSanitizer def initialize(app) @app = app end def call(env) if env['CONTENT_TYPE'] =~ /multipart\/form-data/ begin Rack::Multipart.parse_multipart(env) rescue EOFError => ex # set content-type to multipart/form-data without the boundary part # to handle the case where empty content is submitted env['CONTENT_TYPE'] = 'multipart/form-data' end end @app.call(env) end end config/initializers/rescue_json_parse_errors.rb class RescueJsonParseErrors def initialize(app) @app = app end def call(env) begin @app.call(env) rescue ActionDispatch::ParamsParser::ParseError => _e return [ 400, {'Content-Type' => 'application/json'}, [{error: 'There was a problem in the your JSON'}.to_json] ] end end end
apprication.rbへ追加します
module Api class Application < Rails::Application config.time_zone = 'Tokyo' config.i18n.default_locale = :ja #ここから config.middleware.insert_before ActionDispatch::ParamsParser, 'RescueJsonParseErrors' config.middleware.insert_before Rack::Runtime, 'BadMultipartFormDataSanitizer' #ここまで config.generators do |g| g.test_framework :rspec, fixtures: true, view_specs: true, helper_specs: false, routing_specs: true, controller_specs: true, request_specs: true g.fixture_replacement :factory_girl, dir: "spec/factories" end config.middleware.insert_before 0, "Rack::Cors" do allow do origins '*' resource '*', :headers => :any, :expose => ['access-token', 'expiry', 'token-type', 'uid', 'client'], :methods => [:get, :post, :options, :delete, :put] end end end end
それからリクエストを送ったら無事データを受信できました
Started POST "/api/file" for ::1 at 2019-09-18 18:57:13 +0900 ActiveRecord::SchemaMigration Load (0.9ms) SELECT `schema_migrations`.* FROM `schema_migrations` Processing by VariousStuff::VariousController#file as */* -------------------------adsadsadsa {"controller"=>"various_stuff/various", "action"=>"file"} -------------------------dsadsa Completed 500 Internal Server Error in 11ms (ActiveRecord: 0.0ms)
参考記事
コメントを残す