I am struggling with a VueJS project function supposed to make a GET request on the server. It throws an error while this syntax has always been working so far in the rest of the website.
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')
})
}
In this situation, the console prints the expected list of existingUsers, but then throw the following error:
Error in callback for watcher "existingMembers": "TypeError: str.replace is not a function"
(the code is executed in a watcher for existingUsers).
I have tried to empty the callback to:
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 => { })
But the same error is thrown. Any idea what could the problem be?
From what I saw debugging, the headers can't pass an array to the server this way.
I decided to pass the array as a string(
this.usersResource = this.$resource('http://127.0.0.1:3000/api/users', {}, {}, {
headers: {
existingUsers: this.existingUsers.toString()
}
)
and to reconstruct it on the other side as an array, but there might be other solutions / packages that allow sending directly arrays via HTTP GET requests.
As you can see in specification there are no words about the type of value in HTTP headers. But, as far as I know, if you use additional libraries, you can pass only String
as header value.
And your answer is partly right. But I suggest you to avoid using .toString
in this case.
Let's imagine the situation when one of existingMembers
has no userId
. In this case, you will get in existingUsers
something like this ["ID00101", undefined, "ID01001"]
. After the execution of .toString()
function inside header you will get
headers: { existingUsers: "ID00101,,ID01001" }
So it will be hard to parse.
Solution
I suggest using JSON.stringify
function
So you can get string like this "["ID00101",null,"ID01001"]"
Your code can be transformed to
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 => { })
And then parse it with JSON.parse
function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.