2017-08-23 41 views
0

我在我的Vue项目中使用axios,并且其中一个对我的api的调用涉及POST。我的帖子和获取都要求使用我的令牌设置Authorization标头。所有get请求做工精细,但将完全一样的头在axios.post导致403axios.post不发送auth头(但.get)

这里是我的爱可信代码:

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以上(并且将GET方法添加到我的api代码中,除了现有的POST,OPTIONS)之外,它将执行得很好。我想我可以这样离开它,但我认为当真的执行POST时,使用GET呼叫是不好的做法。有什么我缺少关于与axios形成POST请求吗?

+0

什么消息都在控制台做一个帖子的时候得到些什么? –

回答

1

Axios Post请求假定第二个参数是数据,第三个参数是config。

Axios Get request假定第二个参数是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) 
}) 
+0

谢谢,不敢相信我错过了! – Stephen