Ananda Vj
Ananda Vj

Reputation: 181

Axios Get Authorization Not Working In Vue But Worked on POSTMAN (Post method on vue worked)

I'm Using vue for the clientside. And somehow the Authorization is not working with Get method in axios. I tried using POSTMAN and it's working like it should be. Is there any chance that I missed something?

getCurrentPeriode() {
    return new Promise((resolve, reject) => {
        axios.get(TABLE_NAME,{params: {"X-API-KEY": API_KEY, command:"getCurrent"}}, {
            headers:{
                'Authorization': `Basic ${token}`
            }
        })
            .then((response) => {
                resolve(response.data[0])
            }) .catch(err => {
                reject(err.response.data)
            })
    })
}

The token:

const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')

I get this error: Uncaught (in promise) {status: false, error: "Unauthorized"}

In postman (it's worked): Postman Get

I've tried with post method in axios and it's working. Yes I've set up CORS. Yes I've allowed Get method in my server side (coz it's working in postman)

Post method is working like normal, here's the code:

postNewPeriode(date) {
    return new Promise((resolve, reject) => {
        const data = new FormData()
        data.append("dateStart", date.dateStart)
        data.append("dateEnd", date.dateEnd)
        data.append("X-API-KEY",API_KEY)
        axios.post(TABLE_NAME,data, {
            headers:{
                "Content-Type": "application/x-www-form-urlencoded",
                "Authorization": `Basic ${token}`
            }
        })
            .then((response) => {
                resolve(response)
            }) .catch(err => {
                reject(err.response.data)
            })
    })
},

Am I missing something in my axios get or I should use different approach? Thanks for the answer

Upvotes: 0

Views: 327

Answers (1)

BogdanC
BogdanC

Reputation: 2784

For Axios GET, the headers should be the second argument, while for PUT and POST the body is the second and the headers the third, as you did. Try using the headers as the second argument on GET.

This should work:

axios.get( TABLE_NAME, 
          { 
            headers:{'Authorization': `Basic ${token}`}, 
            params: {"X-API-KEY": API_KEY, command:"getCurrent"}
          }
         )

Upvotes: 1

Related Questions