无效的请求参数:将文件上载到仅Rails api服务器时的%-encoding无效

时间:2016-11-18 20:02:45

标签: ruby-on-rails rack rackattack rack-cors

我正在开发使用Reactjs作为前端和Rails5 api only应用作为后端的网络应用

这是我作为Request payload

发送到服务器的数据
------WebKitFormBoundaryCD1o71UpVNpU4v86
Content-Disposition: form-data; name="user[username]"

oeuoeoaeaoe
------WebKitFormBoundaryCD1o71UpVNpU4v86
Content-Disposition: form-data; name="user[profile_image]"; filename="gggg.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryCD1o71UpVNpU4v86--

这是我的控制器

def update_with_image
    user = current_user
    if user.update_attributes(user_update_params)
      # Handle a successful update.
      render json: user, status: 200
    else
      render json: { errors: user.errors }, status: 422
    end
  end


  private

  def user_update_params
    params.require(:user).permit(:username,:profile_image)
  end

因此,当我尝试将图像上传到Rails服务器时,我收到了此错误

ActionController::BadRequest (Invalid request parameters: invalid %-encoding ("user[username]"

oeuoeoaeaoe
------WebKitFormBoundaryCD1o71UpVNpU4v86
Content-Disposition: form-data; name="user[profile_image]"; filename="gggg.jpg"
Content-Type: image/jpeg

????JFIF????@6"??

??F!1AQ "aq?
#2???B?????$3Rb?%Cr??????       ??A!1A"Qaq?2???BR???#b??3rS?$Cs????
                                                                   ??%)):

rack (2.0.1) lib/rack/query_parser.rb:72:in `rescue in parse_nested_query'
rack (2.0.1) lib/rack/query_parser.rb:61:in `parse_nested_query'

**我使用Rack::CorsRack::Attack作为我的middileware

我该如何解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:0)

在这个问题上浪费了一天。

正确答案在这里:https://stackoverflow.com/a/60812593/11792577

当您使用 fetch 将 Content-Type 发布到 Rails api 服务器时,不要设置 multipart/form-data 标头。

错误

// this is not working
fetch(
  url,
  {
    method: 'POST', // or 'PUT'
    headers: {
       'Content-Type': 'multipart/form-data'
    },
    /*
    * or
    * headers: {
    *   'Content-Type': '',
    *   'Content-Type': undefined,
    *   'Content-Type': null,
    * },
    */
    body
  }
);

正确

fetch(url, {
   method: 'POST',
   headers: {},
   body
});

// or delete headers['Content-Type'] if necessary
相关问题