You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Faraday发起POST请求报参数数量错误(given 2, expected 0..1)如何解决

Faraday POST请求报参数数量错误排查

问题表现

使用faraday gem发送HTTP POST请求时,在代码行response = connection.post '/submissions' do |request|处持续抛出错误wrong number of arguments (given 2, expected 0..1)。尝试调整传参逻辑、参考官方文档改写连接和请求构造代码后,问题仍然复现。

问题代码

def post_submission
  connection = Faraday.new(url: URL, headers: { 'Content-Type' => 'application/json' })
  response = connection.post '/submissions' do |request|
    request.params = { base64_encoded: false, wait: true }
    request.body = JSON.generate(
      source_code: @params[:source_code],
      stdin: @params[:input],
      expected_output: @problem.output,
      anguage_id: @programming_languge.judge_code
    )
  end
end

报错截图

Faraday参数数量不匹配报错截图

根因与修复方案

  • 触发核心原因:Ruby方法无括号调用的语法解析+Faraday版本签名变更共同导致。当前环境安装的Faraday版本中post方法参数签名,在无括号调用传路径+后置block时,Ruby会将block错误识别为第二个位置参数传入,触发参数数量校验报错。
  • 最快修复方式:给post方法的路径参数加上括号,明确参数边界,修正后的代码如下:
def post_submission
  connection = Faraday.new(url: URL, headers: { 'Content-Type' => 'application/json' })
  # 给post方法调用加括号,避免参数解析错误
  response = connection.post('/submissions') do |request|
    request.params = { base64_encoded: false, wait: true }
    request.body = JSON.generate(
      source_code: @params[:source_code],
      stdin: @params[:input],
      expected_output: @problem.output,
      # 顺便修正原代码的拼写错误,避免后续请求参数异常
      language_id: @programming_language.judge_code
    )
  end
end
  • 补充排查项:如果加括号后仍然报错,执行bundle list faraday检查本地安装的Faraday版本,如果Gemfile中锁定的是1.x版本却安装了2.x的依赖文件,执行bundle pristine faraday重装对应版本gem即可,避免版本文件混装导致的方法签名异常。

内容的提问来源于stack exchange,提问作者AbdUlRahman Shawareb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 04:21:24