如何使用 Axios 将 JSON 数据正确发送到 rails 服务器,以正确匹配所需的 rails 参数散列?

How to send JSON data correctly using Axios to a rails server, to match the required rails params hash correctly?

我正在向 rails 服务器发出 GET 请求,参数应如下所示:

{"where"=>{"producer_id"=>["7"]}

我正在从 Vue 中的前端应用程序发出请求,并使用 Axios 发出请求。我是这样提出请求的:

const data = await this.axios.get('http://localhost:3000/data.json', {
  headers: {
    'X-User-Token': this.$store.getters.authToken,
    'X-User-Username': this.$store.getters.user.username
  },
  params: {
    where: {
      producer_id: data.producers
    }
  }
})

但是,在 rails 服务器输出中显示参数是这样发送的:

{"where"=>"{\"producer_id\":[\"7\"]}"}

因此我没有得到正确的数据。

我该如何解决这个问题?为什么 paramswhere 对象)中的第二级作为字符串发送?

事实证明,在这种情况下,参数必须被序列化 https://github.com/axios/axios/issues/738

我也使用了 paramsSerializer 函数来克服这个问题

const data = await this.axios.get('http://localhost:3000/data.json', {
  headers: {
    'X-User-Token': this.$store.getters.authToken,
    'X-User-Username': this.$store.getters.user.username
  },
  params: {
    where: {
      producer_id: data.producers
    }
  },
  paramsSerializer: function (params) {
    return jQuery.param(params)
  }
})

编辑:

我现在使用 qs 而不是 jQuery:

axios.defaults.paramsSerializer = (params) => {
  return qs.stringify(params, {arrayFormat: 'brackets'})
}