【问题标题】:axios.post not sending auth header (but .get does)axios.post 不发送 auth 标头(但 .get 发送)
【发布时间】:2018-02-01 10:27:19
【问题描述】:

我在我的 Vue 项目中使用 axios,对我的 api 的调用之一涉及到 POST。我的帖子和获取都要求使用我的令牌设置 Authorization 标头。所有获取请求都可以正常工作,但将完全相同的标头放入 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 错误,并且检查我的请求标头显示授权标头从未发送过。如果我将上面的axios.post 更改为axios.get(并在我的api 代码中添加一个GET 方法,除了现有的POST,OPTIONS),它将执行得很好。我想我可以这样离开它,但我认为在真正执行POST 时使用GET 调用是不好的做法。关于使用 axios 形成 POST 请求,我有什么遗漏吗?

【问题讨论】:

  • 您在发帖时在控制台中收到什么消息?

标签: vue.js axios


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 2018-08-14
  • 2018-03-18
  • 2015-06-07
  • 2020-08-16
  • 1970-01-01
  • 2021-08-11
  • 2017-05-29
  • 1970-01-01
相关资源
最近更新 更多