繁体   English   中英

GET请求引发错误:str.replace不是函数

[英]GET request throws error: str.replace is not a function

我正在为应该在服务器上发出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列表,但随后会引发以下错误:

监视者“ existingMembers”的回调错误:“ TypeError:str.replace不是函数”

(该代码在观察者中为existingUsers执行)。

我试图清空回调到:

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 => { }) 

但是会引发同样的错误。 知道可能是什么问题吗?

从调试的角度看,标头无法以这种方式将数组传递给服务器。

我决定将数组作为字符串传递(

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

并在另一端将其重构为数组,但可能还有其他解决方案/程序包允许通过HTTP GET请求直接发送数组。

正如您在规范中所看到的,HTTP头中没有关于值类型的字词。 但是,据我所知,如果您使用其他库,则只能传递String作为标头值。

您的答案部分正确。 但我建议您在这种情况下避免使用.toString

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

标头:{existingUsers:“ ID00101,,ID01001”}

因此将很难解析。

我建议使用JSON.stringify 函数

这样就可以得到像这样的字符串"["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 函数解析

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM