【问题标题】:How to fix 400 Bad Request for JavaScript fetch API PUT如何修复 JavaScript fetch API PUT 的 400 Bad Request
【发布时间】:2019-12-24 04:35:40
【问题描述】:

我正在向我的 Rails 服务器发出 PUT 请求以更新项目数组中的项目。我的项目包括 ID、名称和描述。当我发出 PUT 请求时,我收到响应 400 Bad Request。此外,我收到此错误:

ActionController::ParameterMissing(参数丢失或值为空:item):
app/controllers/api/v1/items_controller.rb:24:in 'item_params'
app/controllers/api/v1/items_controller.rb:17:in '更新'

我已尝试以不同方式格式化请求,以查看项目是否未正确格式化。我查找了类似的帖子,但它们似乎没有涵盖我的确切请求方法或没有显示类似类型的对象。

我当前要更新的函数如下所示:

 handleUpdate = (item) => {
    const id = item.id;
    fetch(`/api/v1/items/${id}`, {
      method: 'PUT',
      body: JSON.stringify({
        'item': item
      })
    }).then(() => {
      this.updateItems(item);
    }).catch(function (error) {
      console.log(error);
    })
  }

这是我的 items_controller:

def update
    item = Item.find(params["id"])
    item.update_attributes(item_params)
    respond_with item, json: item
  end

  private

  def item_params
    params.require(:item).permit(:id, :name, :description)
  end

这是我通过调用 handleUpdate 函数创建的对象:

const item = {
        'id': id,
        'name': this.state.name,
        'description': this.state.description
      };
      this.props.handleUpdate(item);

我的状态正在正确更新,但错误阻止我的数据库正确更新项目。

【问题讨论】:

    标签: javascript ruby-on-rails reactjs put fetch-api


    【解决方案1】:

    由于您在 params.require(:item) 中需要“item”,因此您的请求需要父级“item”键

    {"item": { "id": id, "name": "somename", "description": "some desc." }}
    

    【讨论】:

    • 其实,这只是我需要做的一部分。我添加了一个内容类型为 application/json 的标题,效果很好。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 2020-02-29
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多