1
votes

I look for an answer this morning and try lot of things but my axios API Call always failed with a 401 error.

Furthemore if I try a curl from the console or postman the request works and I don't understand why on my front with vue and axios it's failed.

I tried to pass the bearer globally, then for a unique route

First of all I have the configuration of my module for Axios

export default() => {
  return axios.create({
    baseURL: process.env.VUE_APP_API,
    headers: { 
        'Content-Type': 'application/json',
        Authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyIn0.wxYD9dllTqT1gAIBmwo35Z4Q4qmlDZwXqz9FdYqXZnU'
    }
  })
}

Then I have my request

Api().get(`user-profiles/${id}`).then(function (response) {
        return(response)
      })

The request is this one:

Request URL: https://***
Request Method: OPTIONS
Status Code: 401 
Remote Address: ****
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, DELETE, PUT, PATCH
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Location
Provisional headers are shown
Access-Control-Request-Headers: authorization
Access-Control-Request-Method: GET
Origin: http://localhost:8080
Referer: http://localhost:8080/login
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Mobile Safari/537.36

Do you need other data ? The request works if I don't use a Bearer token...

I need to pass a Bearer token because for production release I can't take off the bearer.

Thank you in advance for your help.

2
Tried this way ? => axios.defaults.headers.common['Authorization'] = 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyIn0.wxYD9dllTqT1gAIBmwo35Z4Q4qmlDZwXqz9FdYqXZnU'Riddhi
Open the Chrome DevTools by pressing F12, then goto the Network tab and filter the requests by type XHR. Then look what is actually sent by Axios.IVO GELOV
@Riddhi unfortunatelly already tried but it's not workingBrugher
@IVOGELOV I add in the post the request in networks... But that don't help me ;(Brugher

2 Answers

1
votes

After some search I found the solution... You need to authorize the backend with cors policies... On my own backend in node js that works... I wait the fix for the java api backend ;)

1
votes

How to set header and options in axios?

Like mentioned here in the best answer, you should go for

export default() => {
  return axios.create({
    baseURL: process.env.VUE_APP_API,
    headers: { 
      'get': {
        'Content-Type': 'application/json',
        Authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyIn0.wxYD9dllTqT1gAIBmwo35Z4Q4qmlDZwXqz9FdYqXZnU'
      }
    }
  })
}