Unexpected error - Axios can not read properties - laravel

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":"test#gmail.com","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 : )

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.

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.

Related

Get Laravel public path in external js file

I have blade file named index-game.blade.php. And in one line of it, a line that reaches a js file under laravel public folder.
<script type="text/javascript" src="{{asset('game/')}}/js/CPreloader.js"></script>
So far so good.
Also inside CPreloader.js, I have lines like this.
s_oSpriteLibrary.addSprite("bg_menu","./sprites/bg_menu.jpg");
s_oSpriteLibrary.addSprite("progress_bar","./sprites/progress_bar.png");
At this stage, I get the following error in the console of my browser's devtools screen:
bg_menu.jpg:1 GET http://127.0.0.1:8000/games/sprites/bg_menu.jpg 404 (Not Found)
progress_bar.png:1 GET http://127.0.0.1:8000/games/sprites/progress_bar.png 404 (Not Found)
This is the link where I called "index-game.blade.php" => http://127.0.0.1:8000/games/slot1 (Let's pay attention to the games word here)
It works if i change my javascript file to
s_oSpriteLibrary.addSprite("bg_menu","../game/sprites/bg_menu.jpg");
s_oSpriteLibrary.addSprite("progress_bar","../game/sprites/progress_bar.png");
Because the correct link is this instead
http://127.0.0.1:8000/games/sprites/bg_menu.jpg // wrong
http://127.0.0.1:8000/game/sprites/bg_menu.jpg // true
I don't want to change the paths in all my javascript files. Because this is a game and there are as many pictures as possible. How do I correctly identify the laravel public folder in my external js files.
There is a package for that: https://github.com/tighten/ziggy
Some copy/paste from docs:
Install Ziggy into your Laravel app with
composer require tightenco/ziggy
Generate javascript route file:
php artisan ziggy:generate
Import in js file and use:
// app.js
import route from 'ziggy';
import { Ziggy } from './ziggy';
// ...
route('home', undefined, undefined, Ziggy);

Laravel + vue.js : vue devtools only showing <Root> compenent

I have a little problem with vue.js recently and wondering if anyone could help please?
I have a new install of laravel 7.3.3 and vue.js 2.6.12 can not get the vue devtools extension to show me my components, variables etc.
This is what the devtools look like :
Here is the repo : https://github.com/yex777/pa-hub
Thanks for any help!
I had a similar issue with my repo. I don't actually register components globally, I instead make components and just register them on the page they are needed. My issue with this was caused because I was binding Vue to the page twice. Once in app.js and then again in my custom JS file for my component. As such, I think the dev tools was picking up the wrong Vue instance.
I resolved my issue by removing the references to vue in my app.js file and then only binding elements using my new JS file. So my app.js file only contains
require('./bootstrap');
and then I have a separate file which I include on the relevant page which looks a little like this:
import Vue from 'vue';
import Axios from 'axios';
import StudentManagement from './StudentManagement.vue';
window.axios = Axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
new Vue({ // eslint-disable-line no-undef, no-new
el: '#student-management',
render: h => h(StudentManagement),
});
I suspect you may have a similar issue where the Vue instance is being setup twice.
The easiest way to check is in the console, it will output a message saying that Vue is in development mode:
As you can see, it's got a 2 next to the message, saying the message has been output twice. If this is the case, you just need to make sure you only include or set up your Vue instance once and the dev tools should pickup your components.

How to properly connect Nuxt.js with a laravel backend?

I am starting a new project, Nuxt.js for the frontend and Laravel for the backend.
How can I connect the two?
I have installed a new Nuxt project using create-nuxt-app, and a new laravel project.
As far as I have searched, I figured I need some kind of environment variables.
In my nuxt project, I have added the dotenv package and placed a new .env file in the root of the nuxt project.
And added CORS to my laravel project, as I have been getting an error.
The variables inside are indeed accessible from the project, and im using them
like this:
APP_NAME=TestProjectName
API_URL=http://127.0.0.1:8000
And accessing it like this:
process.env.APP_NAME etc'
To make HTTP calls, I am using the official Axios module of nuxt.js, and to test it i used it in one of the components that came by default.
The backend:
Route::get('/', function () {
return "Hello from Laravel API";
});
and from inside the component:
console.log(process.env.API_URL)//Gives 127.0.0.1:8000
//But this gives undefined
this.$axios.$get(process.env.API_URL).then((response) => {
console.log(response);
});
}
What am I doing wrong here?
I have tried to describe my setup and problem as best as I can. If I overlooked something, please tell me and I will update my question. Thanks.
Taking for granted that visiting https://127.0.0.1:8000/ in your browser you get the expected response, lets see what might be wrong in the front end:
First you should make sure that axios module is initialized correctly. Your nuxt.config.js file should include the following
//inclusion of module
modules: [
'#nuxtjs/axios',
<other modules>,
],
//configuration of module
axios: {
baseURL: process.env.API_URL,
},
Keep in mind that depending on the component's lifecycle, your axios request may be occurring in the client side (after server side rendering), where the address 127.0.0.1 might be invalid. I would suggest that you avoid using 127.0.0.1 or localhost when defining api_uris, and prefer using your local network ip for local testing.
After configuring the axios module as above, you can make requests in your components using just relative api uris:
this.$axios.$get('/').then(response => {
console.log(response)
}).catch(err => {
console.error(err)
})
While testing if this works it is very helpful to open your browser's dev tools > network tab and check the state of the request. If you still don't get the response, the odds are that you'll have more info either from the catch section, or the request status from the dev tools.
Keep us updated!
Nuxt has a routing file stucture to make it easy to set up server side rendering but also to help with maintainability too. This can cause Laravel and Nuxt to fight over the routing, you will need to configure this to get it working correctly.
I'd suggest you use Laravel-Nuxt as a lot of these small problems are solved for you.
https://github.com/cretueusebiu/laravel-nuxt

Vuejs Axios POST request gets HTTP422 error from Laravel backend

Hi I am using Vuejs in the frontend and Laravel in the backend. The role of Laravel is handling the API only. The frontend and backend are separated, i.e. I am not using Vuejs in Laravel's resource/js folder.
Now I am sending Axios POST request from Vuejs to Laravel. All the form input values are prevalidated using HTML5 required attribute. And when I console.log the request data, it shows all the fields filled.
In Vue file:
const data = {
name: this.name,
gender: this.gender,
mobile_no: this.mobile_no,
image: this.userImage
};
console.log("Request data . . . .", data);
const response = await this.axios
.post(`${this.AppURL}/admin/user/create`, data, {
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(() => {
console.log("Success. . . . ")
alert("Successfully Driver Added");
})
.catch(error => console.log(error));
And in Laravel, the request is passed through some validation. It's a simple validation to check if all the fields are filled.
I am also using JWTAuth package for the authentication, and the token is generated by it.
It's too much code to write them all the way down here. But I am sure you can understand what I mean.
What I am getting as a response is this
POST http://localhost:8000/api/admin/user/create 422 (Unprocessable Entity)
The actual result I am expected to get is either success or some errors that is according to some if conditions in validation or token check.
I tried to figure out where this error might come from. What I think at the moment is this could be due to the absence of csrf_token in the POST request. As I'm sending the request outside Laravel, csrf_token is missing in the form. I am not 100% sure though about this.
So my question is:
How can I include csrf_token in Axios POST request, when I send it from outside Laravel.
If this 422 error is not related with csrf_token, what could be causing this? Any previos experiences like min? and any solutions for this?
Thanks in advance for your help.
Please, modified catch block as #Jack suggested:
.catch(error => {
console.log("ERRRR:: ",error.response.data);
});
Now you can get errors and handle errors in the catch block.
.catch(function (error) {
console.log(error.response.data.errors);
});
please use this code I hope it work's.
I was also facing the same issue, i think it is due to some Headers missing in your Api request from vue.js. here some tips which may helps you to solve this issues.
Make sure that you are protecting your Api Routes or not(by sanctum or something else). If you are protecting , then make make sure that you are sending authentications token in headers.
Second make sure that your request(axios or jwt) should contained valid data, if your are sending images or files etc make sure how can we send them.
First, get request and check in laravel by dd($erquest->all()); if you are geeting data then validate, it is possible that laravel request doesnt contained your sending data..
These errors may be caused due to follow reasons, ensure the following steps are followed.
To connect the local host with the local virtual machine(host).
Here, I'am connecting http://localhost:3001/ to the http://abc.test
Steps to be followed:
We have to allow CORS, placing Access-Control-Allow-Origin:* in header of request may not work. Install a google extension which enables a CORS request.
Make sure the credentials you provide in the request are valid.
Make sure the vagrant has been provisioned. Try vagrant up --provision
this make the localhost connect to db of the homestead.
Just click on the preview tab within network section in the dev tool, you are going to see the actual error message.

How to use Vue.js plugins and components in Laravel

I am using Vue.js (within the Laravel framework) and I'm new to both. I'm trying to understand some basic ideas about some code I"m trying to use:
App.js:
import Vue from 'vue';
import Toasted from 'vue-toasted';
Vue.component('toast-alert', require('./components/ToastAlert.vue'));
Vue.use(Toasted);
ToastAlert.vue:
<template>
</template>
<script>
export default {
props: {
},
mounted() {
this.showToast()
},
data() {
return {
message: 'Status Update',
}
},
methods: {
showToast() {
this.$toasted.show(this.message, {
duration: 3000
});
}
}
}
</script>
Questions:
I understand the import tells the script that we ant to pull in certain node modules but I don't totally understand what use() is for. I have read documentation to see thats what you do with plugins (https://v2.vuejs.org/v2/guide/plugins.html), but not really understanding more than that.
Again from the documentation, I see that when registering a Vue component, the second parameter is a list of options, ie: template, props, methods etc. I'm a bit confused about what require does and how it translates the vue file (which is a composed of tags and a tag exporting an object) into a final object which meets the standards of Vue.component.
1) In Vue, calling Vue.use( Plugin, Options ) makes the plugin available throughout the application. It's basically a way to bootstrap a plugin i.e. Vue-Toasted, so you can use it throughout your application. You can define configuration options as well here.
2) Vue.component is used to register (your own) components in the application. It allows them to be used within each other component, without having to define them in each file. Think of the app.js file as the bootstrap file, it defines all of the plugins, components, etc. and registers them for use in Vue. require is importing the file and Vue is parsing the template and object. Note this is all compiled in webpack and cannot load in a browser as-is.

Resources