axios.post 未发送身份验证 header(但 .get 发送)
axios.post not sending auth header (but .get does)
我在我的 Vue 项目中使用 axios,对我的 api 的调用之一涉及 POST
。我的帖子和获取都要求使用我的令牌设置 Authorization
header。所有 get 请求都工作正常,但是将完全相同的 headers 放入 axios.post
会导致 403.
这是我的 axios 代码:
axios.post('https://my.example.org/myapi/meta?uname=' + uname + '&umetaid=' + post.umeta_id + '&umetavalue=' + post.meta_value, {
withCredentials: true,
headers: { 'Authorization': 'Bearer ' + mytoken }
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
这总是导致 403 错误,检查我的请求 header 显示授权 header 从未发送过。如果我将上面的 axios.post
更改为 axios.get
(并在我的 api 代码中添加一个 GET
方法,除了现有的 POST,OPTIONS
之外),它只会执行美好的。我想我可以这样保留它,但我认为在真正执行 POST
时使用 GET
调用是不好的做法。关于使用 axios 形成 POST
请求,我是否遗漏了什么?
axios Post请求假设第二个参数是data,第三个参数是config.
Axios Get请求假定第二个参数为config,而数据附加在URL。
您正在 url 中发送数据,这应该作为第二个参数(对于 POST 请求)。
代码应该是:
var data = {
'uname': uname,
'umetaid': post.umeta_id,
'umetavalue': post.meta_value
}
var headers = {
withCredentials: true,
headers: { 'Authorization': 'Bearer ' + mytoken }
}
axios.post('https://my.example.org/myapi/meta',data,headers)
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
我在我的 Vue 项目中使用 axios,对我的 api 的调用之一涉及 POST
。我的帖子和获取都要求使用我的令牌设置 Authorization
header。所有 get 请求都工作正常,但是将完全相同的 headers 放入 axios.post
会导致 403.
这是我的 axios 代码:
axios.post('https://my.example.org/myapi/meta?uname=' + uname + '&umetaid=' + post.umeta_id + '&umetavalue=' + post.meta_value, {
withCredentials: true,
headers: { 'Authorization': 'Bearer ' + mytoken }
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
这总是导致 403 错误,检查我的请求 header 显示授权 header 从未发送过。如果我将上面的 axios.post
更改为 axios.get
(并在我的 api 代码中添加一个 GET
方法,除了现有的 POST,OPTIONS
之外),它只会执行美好的。我想我可以这样保留它,但我认为在真正执行 POST
时使用 GET
调用是不好的做法。关于使用 axios 形成 POST
请求,我是否遗漏了什么?
axios Post请求假设第二个参数是data,第三个参数是config.
Axios Get请求假定第二个参数为config,而数据附加在URL。
您正在 url 中发送数据,这应该作为第二个参数(对于 POST 请求)。
代码应该是:
var data = {
'uname': uname,
'umetaid': post.umeta_id,
'umetavalue': post.meta_value
}
var headers = {
withCredentials: true,
headers: { 'Authorization': 'Bearer ' + mytoken }
}
axios.post('https://my.example.org/myapi/meta',data,headers)
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})