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

Var*_*kul 6 rack ruby-on-rails rackattack rack-cors

我正在开发Reactjs用作前端和Rails5 api only应用程序作为后端的Web应用程序

这是我发送到服务器的数据 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--
Run Code Online (Sandbox Code Playgroud)

这是我的控制器

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
Run Code Online (Sandbox Code Playgroud)

所以当我试图将图像上传到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'
Run Code Online (Sandbox Code Playgroud)

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

我怎样才能解决这个问题?

谢谢!

gli*_*a93 5

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

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

Content-Type当您使用 fetch 发布到 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
  }
);
Run Code Online (Sandbox Code Playgroud)

正确的

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

// or delete headers['Content-Type'] if necessary
Run Code Online (Sandbox Code Playgroud)