【问题标题】:How save multiple params in variable and add to in url? [duplicate]如何在变量中保存多个参数并添加到 url 中? [复制]
【发布时间】:2019-11-06 23:58:21
【问题描述】:

我有很多参数想保存在param 变量中,并将其添加到url

如何将这个参数filter% 5Binprogress% 5D = true保存在变量param中? expand 没有问题 --> expand: track

在tab网络中返回-->"https://spotify?expand=track&filter%255Binprogress%255D=true"

应该是 --> "https://spotify?expand=track&filter%5Binprogress%5D=true"

%255D ---> should be %5D

const param = {
    expand: track,
    'filter%5Binprogress%5D': true  //problem here
}


axios({
    url: "https://spotify?expand=track&filter%5Binprogress%5D=true",
    method: "GET",
    headers: {
        'Authorization': .....
    },
    param: param
})

【问题讨论】:

  • expand 是有效的identifier,为什么有问题?这是一个非常基本的 JS 错误,与 React、Axios 甚至 HTTP 无关:无效标识符需要引用为对象属性名称。
  • 记录filter% 5Binprogress% 5D: true是否正确?
  • 不,不是,这就是您收到错误消息的原因。参见例如stackoverflow.com/q/4348478/3001761解释。
  • 等等,糟糕的骗子。没看错……
  • 我猜stackoverflow.com/questions/4348478/… 是正确的。我找不到专门针对“什么是有效的属性名称”的问题。 this question 很接近,但仍然是前一个的欺骗。

标签: javascript axios


【解决方案1】:

这是因为你在对象属性中有一个特殊字符。

尝试使用引号(单引号或双引号)

const param = {
    expand: track,
    "filter%5Binprogress%5D": true
}


axios({
    url: "https://spotify?expand=track&filter%5Binprogress%5D=true",
    method: "GET",
    headers: {
        'Authorization': .....
    },
    param: param
})


【讨论】:

    【解决方案2】:

    使用引号或使用括号表示法。

    const param = {
        expand: track
    }
    
    param['filter%5Binprogress%5D'] = true;
    

    或者使用引号:

    const param = {
            expand: track,
            "filter%5Binprogress%5D": true 
    
        }
    

    【讨论】:

    • { 'filter%5Binprogress%5D': true } 是一个有效的对象字面量。
    • 是的 - 编辑了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 2011-09-27
    • 2017-03-06
    • 1970-01-01
    相关资源
    最近更新 更多