Home > Enterprise >  Unexpected error - Axios can not read properties
Unexpected error - Axios can not read properties

Time:01-29

for a real time project i use laravel 8 and axios javascript library used to make HTTP requests. the backend work great . for example if go to this URL http://127.0.0.1:8000/api/usersthe following data will be show

[{"id":1,"name":"Hossein Khosromanesh","email":"[email protected]","email_verified_at":null,"created_at":"2022-01-22T19:52:12.000000Z","updated_at":"2022-01-22T19:52:12.000000Z"}]

the problem comes when i want to show the data to the frontend , we got error Uncaught TypeError: Cannot read properties of undefined (reading 'get') at users:84:18

actually get('/api/users') from window.axios.get('/api/users') is the main problem

the front end code :

<script>
    
    window.axios.get('/api/users')
        .then((response) => {
            const usersElement = document.getElementById('users')
            let users = response.data
            users.ForEach((user,index) => {
                let element = document.createElement('li')
                element.setAttribute('id' , user.id)
                element.innerText = user.name
    
                usersElement.appendChild(element)
    
            })
    
        })
    
    </script>

what's wrong was my code ? can somebody please help me and free me from darkness : )

CodePudding user response:

If you are importing axios using a script tag in your html or blade file, you can use it with axios.get instead of window.axios.get.

CodePudding user response:

As per My understanding from your code. You have to import axios in vue component or view where you consume API like below.

import axios from "axios";

Then You can use it like

axios.get('/api/users').then();

Note:- No need to register axios inside windows object in app.js for more information please refer below link

https://axios-http.com/docs/intro

If above method still not work for you then follow below step

Take backup of your code first then perform below step

  1. Check your package.json file and verify axios is present over there or not.
  2. If you don't find then install it using npm command
  3. If you find then delete your package.lock.json file and run npm install command
  4. Then follow import step mentioned above and try.
  •  Tags:  
  • Related