Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rafidAhsan's avatar

401 (Unauthorized) on axios post request on vue 2

I am working on a project on vue 2 my api is receiving bearer token and working on postman. But on actual vue 2 app is not working.

validationForm() {
      const config = {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Authorization: `${localStorage.getItem('access_token')}`, // : `Bearer ${localStorage.getItem('access_token')}`, also not working
        },
      }

      const bodyParameters = {
        first_name: this.first_name,
        middle_name: this.middle_name,
        last_name: this.last_name,
        dob: this.dob,
        gender: this.gender,
        bio: this.bio,
      }

      this.$refs.simpleRules.validate().then(success => {
        if (success) {
          axios.post('/basic-details',
            bodyParameters,
            config).then(response => {
            console.log(response)
          })
        }
      })
    }

and on login

    localStorage.setItem('access_token', response.data.accessToken)
0 likes
16 replies
mediabloke's avatar

Change this

Authorization: `${localStorage.getItem('access_token')}`,

to Authorization: `Bearer ${localStorage.getItem('access_token')}`,

psrz's avatar

If you generate a code snippet using postman, what are the headers that is sending on the request that is working?

Also, is that an api or web route ?

rafidAhsan's avatar

@psrz that is api I merged with the postman's generated code and that is also not working

MaverickChan's avatar

always check if token exists

if not , redirect back to login page

rafidAhsan's avatar

@MaverickChan token exits and output console.log(Bearer ${localStorage.getItem('access_token')}) Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODAwMFwvYXBpXC9sb2dpbiIsImlhdCI6MTY2MTQwNzE1NiwiZXhwIjoxNjYxNDkzNTU2LCJuYmYiOjE2NjE0MDcxNTYsImp0aSI6ImptbmplbzV1VTgyeWRJZGMiLCJzdWIiOjE4LCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.lGcbUSFU37hppqMy7d4Q__5MtzS8BxRvXg15-mnLErA

hammad2010's avatar

401 is unauthorized code you have to pass this $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': "{{ csrf_token() }}" } }); maybe this will help you

rafidAhsan's avatar

@hammad2010 token exits and output console.log(Bearer ${localStorage.getItem('access_token')}) Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODAwMFwvYXBpXC9sb2dpbiIsImlhdCI6MTY2MTQwNzE1NiwiZXhwIjoxNjYxNDkzNTU2LCJuYmYiOjE2NjE0MDcxNTYsImp0aSI6ImptbmplbzV1VTgyeWRJZGMiLCJzdWIiOjE4LCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.lGcbUSFU37hppqMy7d4Q__5MtzS8BxRvXg15-mnLErA

Snapey's avatar

@rafidAhsan I doubt it unless you have a variable called Bearer which happens to contain the string ‘Bearer’

rafidAhsan's avatar

@Snapey sorry I can't understand . But I didn't use any variables to store access token. I used local storage

Snapey's avatar

You have Bearer and the $(local… inside the same string. Check what is actually being sent as the authorisation header in the browser network request

rafidAhsan's avatar

@Snapey no access token presented in request header

but i pass the token in the axios code and

${localStorage.getItem('access_token')})

outputs the exact token

MaverickChan's avatar

you cannot use this

${localStorage.getItem('access_token')})

inside an object define.

use a variable

const token = localStorage.getItem('access_token') || null
if (!token) {
	//redirect to login page
}

then

const config = {
        headers: {
          Authorization:  'Bearer ' +  token,
        },

i don't think you should put content-type , it is all about token, i guess

rafidAhsan's avatar

@MaverickChan I tried this before but still not working

validationForm() {
      const data = {
        first_name: this.first_name,
        middle_name: this.middle_name,
        last_name: this.last_name,
        dob: this.dob,
        gender: this.gender,
        bio: this.bio,
      }

      const token = localStorage.getItem('access_token')

      const config = {
        method: 'post',
        url: '/basic-details',
        headers: {
          Authorization: `Bearer ${token}`,
        },
        data,
      }

      this.$refs.simpleRules.validate().then(success => {
        if (success) {
          axios(config)
            .then(response => {
              console.log(JSON.stringify(response.data))
            })
            .catch(error => {
              console.log(error)
            })
        }
      })
    }
Snapey's avatar

@rafidAhsan and what did your browser send when you did this? You have all the tooling required to solve this simple problem of setting the authorisation header

rafidAhsan's avatar

@Snapey I am sending the full headers of my browser

General
Request URL: http://localhost:8000/api/basic-details
Request Method: POST
Status Code: 401 Unauthorized
Remote Address: 127.0.0.1:8000
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:8080
Cache-Control: no-cache, private
Connection: close
Content-Type: application/json
Date: Fri, 26 Aug 2022 06:17:55 GMT
Date: Fri, 26 Aug 2022 06:17:55 GMT
Host: localhost:8000
phpdebugbar-id: Xd3d750b40de89b27900fe8a4314ef643
Set-Cookie: superio_session=eyJpdiI6IllGcm9UQVZRTWpOYVU4Y3FXc2trekE9PSIsInZhbHVlIjoiTnVwN3Z5NUdOeis4MDl3c1RCUDk1MW85Z3YzS3c1ejR4NVAxRkUvcUY2WlBNeGlPc3RFWUdYaENWb2RObjhuUkM2bW5OOXR0NHA5L1pxZHpGeWNUNUMwdEhNZlNBNUZWdnBTYnp5UWVrbmp2a3RmZXlNVndvSndtNm8rSUxJNW8iLCJtYWMiOiJmYjk1YjlkODQ0NTZmMjRiMzc2NzkzYTRhNGY0OTFmZDYzNzJlNGI0MTg5ZDAyMzAwMGY4NTI4YjU1OTY1YjM4In0%3D; expires=Fri, 26-Aug-2022 08:17:55 GMT; Max-Age=7200; path=/; httponly
Vary: Origin
X-Powered-By: PHP/7.4.27
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 57
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,bn;q=0.8
Access-Control-Allow-Origin: *
Authorization: Bearer undefined
Connection: keep-alive
Content-Length: 134
Content-Type: application/json;charset=UTF-8
Host: localhost:8000
Origin: http://localhost:8080
Referer: http://localhost:8080/
sec-ch-ua: "Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36

Please or to participate in this conversation.