一个值得的队伍

问题描述 投票:1回答:2
axios.get(globalConfig.FAKE_API, {
    params: {
        phone: this.phone,
        mail: this.mail
    },
})
.then((resp) => {
    this.req = resp.data
 })
.catch((err) => {
     console.log(err)
 })

在使用Axios执行GET / POST请求时,有什么办法可以创建条件参数吗?例如,如果我的mail参数为空,我将不会发送空参数,例如:someurl.com?phone=12312&mail=

javascript axios
2个回答
4
投票

您可以在发出请求之前维护params变量,只有在有以下数据时才添加密钥:

const params = {}
if (this.mail) { params.mail = this.mail }

或者你可以这样做,我们在...()括号之间编写正常的js代码。我们正在增加一个三元条件。

axios.get(globalConfig.FAKE_API, {
  params: {
    phone: this.phone,
    ...(this.mail ? { mail: this.mail } : {})
  },
})

1
投票

Raghav Garg的想法乍一看看起来很整洁,但是有一个以上的可选参数,我担心它会变得混乱。

你可以简单地使用一个常见的实用程序库,如下划线或lodash,并使用他们的filter函数:

const allParams = {
    mail: this.mail,
    phone: this.phone,
    // ...
};
axios.get(globalConfig.FAKE_API, {
   // 'Pick' takes only those elements from the object
   // for which the callback function returns true
   //
   // Double negation will convert any value to its boolean value,
   // so null becomes false etc.
   params: _.pick(allParams, (value, key) => { return !!value; })
})
© www.soinside.com 2019 - 2024. All rights reserved.