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
- Check your package.json file and verify axios is present over there or not.
- If you don't find then install it using npm command
- If you find then delete your package.lock.json file and run npm install command
- Then follow import step mentioned above and try.
