gpt4 book ai didi

javascript - GET 请求抛出错误 : str. replace is not a function

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:23:39 25 4
gpt4 key购买 nike

我正在努力处理应该在服务器上发出 GET 请求的 VueJS 项目函数。到目前为止,此语法在网站的其余部分一直有效,但会引发错误。

this.existingUsers = this.existingMembers.map(a => a.userId)

console.log(this.existingUsers)

this.usersResource = this.$resource('http://127.0.0.1:3000/api/users', {}, {}, {
headers: {
existingUsers: this.existingUsers
}
})

this.usersResource.get().then(response => {
// If server answer
if (response.body.success) {
// Good request
console.log('1')
} else {
// Wrong request
console.log('2')
}
}, _ => {
// The server doesn't answer
console.log('3')
})
}

在这种情况下,控制台会打印预期的 existingUsers 列表,但随后会抛出以下错误:

Error in callback for watcher "existingMembers": "TypeError: str.replace is not a function"

(代码在现有用户的观察者中执行)。

我试图将回调清空到:

this.existingUsers = this.existingMembers.map(a => a.userId)
console.log(this.existingUsers)
this.usersResource = this.$resource('http://127.0.0.1:3000/api/users', {}, {}, {
headers: {
existingUsers: this.existingUsers
}
})
this.usersResource.get().then(response => { })

但是还是报同样的错误。知道问题出在哪里吗?

最佳答案

正如您在 specification 中看到的那样没有关于 HTTP header 中值类型的文字。但是,据我所知,如果您使用其他库,则只能将 String 作为 header 值传递。

您的回答只对了一部分。但我建议您在这种情况下避免使用 .toString

让我们想象一下 existingMembers 之一没有 userId 的情况。在这种情况下,您将在 existingUsers 中得到类似这样的内容 ["ID00101", undefined, "ID01001"]。在 header 中执行 .toString() 函数后,您将得到

headers: {existingUsers: "ID00101,,ID01001"}

所以很难解析。

解决方案

我建议使用 JSON.stringify function

所以你可以得到这样的字符串 ["ID00101",null,"ID01001"]"

您的代码可以转换为

this.existingUsers = this.existingMembers.map(a => a.userId)
console.log(this.existingUsers)
this.usersResource = this.$resource('http://127.0.0.1:3000/api/users', {}, {}, {
headers: {
existingUsers: JSON.stringify(this.existingUsers)
}
})
this.usersResource.get().then(response => { })

然后用JSON.parse 解析 function

关于javascript - GET 请求抛出错误 : str. replace is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48423143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com