我正在设置一个 CRUD vue 应用程序,通过 axios 与 api 进行通信。我在尝试设置 PATCH 功能时遇到问题
我使用提供此方法的 mixin
axiosPatch (url, body, msg = 'Failed to update data to server') {
return this.$axios.patch(url, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.token
},
body
})
.catch(() => console.log(msg))
}
我在其他地方称之为:
this.axiosPatch('/people/' + this.person.id, { body: { person: { first_name: 'test' } } })
在 api 端我输出:
Started PATCH "/people/712" for 127.0.0.1 at 2019-07-19 00:26:54 +0300
Processing by PeopleController#update as HTML
Parameters: {"headers"=>{"Content-Type"=>"application/json", "Authorization"=>"Bearer ey...w"}, "body"=>{"body"=>{"person"=>{"first_name"=>"test"}}}, "id"=>"712", "person"=>{}}
我预计输出是
...
Parameters: {"headers"=>{"Content-Type"=>"application/json", "Authorization"=>"Bearer ey...w"}, "person"=>{"first_name"=>"test"}, "id"=>"712"}
请问有什么帮助吗?
编辑
方法#1:
this.axiosPatch('/people/' + this.person.id, { person: { first_name: 'test' } })
axiosPatch (url, { body }, msg = 'Failed to update data to server') {
// console.log(body) <-- this outputs 'undefined'
return this.$axios.patch(url, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.token
},
body
}).catch(() => console.log(msg))
}
API output:
Started PATCH "/people/712" for 127.0.0.1 at 2019-07-19 00:26:54 +0300
Processing by PeopleController#update as HTML
Parameters: {"headers"=>{"Content-Type"=>"application/json", "Authorization"=>"Bearer ey...w"}, "id"=>"712", "person"=>{}}
方法#2:
this.axiosPatch('/people/' + this.person.id, { body: { person: { first_name: 'test' } } })
axiosPatch (url, body, msg = 'Failed to update data to server') {
// console.log(body) <-- this outputs the Object correctly
return this.$axios.patch(url, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.token
},
body: body.body
}).catch(() => console.log(msg))
}
API output:
Started PATCH "/people/712" for 127.0.0.1 at 2019-07-19 00:26:54 +0300
Processing by PeopleController#update as HTML
Parameters: {"headers"=>{"Content-Type"=>"application/json", "Authorization"=>"Bearer ey...w"}, "body"=>{"person"=>{"first_name"=>"test"}}, "id"=>"712", "person"=>{}}
最佳答案
问题是您正在添加一个带有键体的对象,您可以通过将 {body}
添加到参数列表来修复它。这将为您提供带有 { person: ... }
axiosPatch (url, {body}, msg = 'Failed to update data to server') {
return this.$axios.patch(url, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.token
},
body
})
.catch(() => console.log(msg))
}
此外,您可以删除传递给 axiosPatch 的参数中的 body 键。
或者你可以这样做:
axiosPatch (url, body, msg = 'Failed to update data to server') {
return this.$axios.patch(url, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.token
},
body: body.body
})
.catch(() => console.log(msg))
}
关于javascript - 如何使用作为函数参数传递的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57136636/