我正在向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'})
}

关于javascript - 如何使用Axios将正确的JSON数据发送到rails服务器,以正确匹配所需的rails params哈希?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47843407/

10-14 17:12
查看更多