Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

axios.post not sending auth header (but .get does)

Tags:

vue.js

axios

I am using axios in my Vue project, and one of the calls to my api involves a POST. Both my posts and gets require that the Authorization header be set with my token. All get requests work fine, but putting the exact same headers in axios.post results in a 403.

Here is my axios code:

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

This always results in a 403 error, and checking my request headers show that the Authorization header is never sent. If I change axios.post to axios.get above (and add a GET method to my api code, in addition to the existing POST,OPTIONS), it will execute just fine. I suppose I could leave it this way, but I think it is bad practice to use a GET call when one really is performing a POST. Is there something I am missing about forming a POST request with axios?

like image 546
Stephen Avatar asked Aug 23 '17 17:08

Stephen


1 Answers

Axios Post request assumes that the second parameter is data and third parameter is config.

Axios Get request assumes that the second parameter is config while the data is appended in URL.

You are sending data in the url which should be as second parameter(For POST request).

Code Should be:

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)
 })
like image 108
Shubham Patel Avatar answered Nov 15 '22 00:11

Shubham Patel