Undefined error in Laravel URL (404 not found) - vue.js

I'm starting with laravel and vue.js. The following code that I am going to show is copied from another code that I have written and it works correctly. I've been looking for days where the error is but I can not find anything. I need this to work in order to continue.
I apologize for the description of the problem but I am not sure how to ask it.
Im getting this error:
I am getting the results of the query correctly. The view loads correctly but does not show the array data.
I can even access other response data:
The route:
Route::get('/oneminuteusers', 'OneMinuteUserController#index');
Component.vue:
<tbody>
<tr v-for="user in usersArray" :key="user.id">
<td v-text="user.user_name"></td>
<td v-text="user.gender"></td>
<td v-text="user.country"></td>
<td v-text="user.games_played"></td>
<td v-text="user.total_clicks"></td>
</tr>
</tbody>
<script>
export default {
data() {
return {
username: "",
country: "",
gender: "",
games_played: "",
total_clicks: "",
usersArray: [],
totalUsers: "",
criterio: "",
buscar: ""
};
},
computed: {
},
methods: {
listUsers(buscar, criterio) {
let me = this;
var url = "/oneminuteusers?buscar=" +buscar +"&criterio=" +criterio;
axios
.get(url)
.then(function(response) {
var respuesta = response.data;
me.usersArray = respuesta.users.data;
me.totalUsers = respuesta.totalusers;
console.log(me.totalUsers);
console.log(response.data);
})
.catch(function(error) {
console.log(error);
});
},
},
mounted() {
this.listUsers(this.buscar, this.criterio);
}
};
</script>

this problem can be raise for CROS.
the request need some headers for allow accessing cross-origin,
for solving the issue change your request as below:
var url = "/oneminuteusers";
data = {
buscar: buscar
criterio: criterio
}
header = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "X-CSRF-TOKEN, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Origin"
}
axios.get(url, data, header)
.then(function(response) {
var respuesta = response.data;
me.usersArray = respuesta.users.data;
me.totalUsers = respuesta.totalusers;
console.log(me.totalUsers);
console.log(response.data);
})
.catch(function(error) {
console.log(error);
});
`

Related

Problem with getting data on current table row in loop

I need a button that makes it possible to follow a listing. So if the button is clicked in the frontend, the listing_id from the listing the button was to the right of, should be send on to the router with a post statement, and on from there to a T-sql database.
At the moment nothing happens when the "follow" button is clicked, but instead the function "followitem(listing)" is triggered whenever the table is loaded.
Currently I get this output when the table loads which contains information on all the listings loaded:
{ userId: '1', listingid: 107 }
{ userId: '1', listingid: 108 }
So to solve this, the button would need to activate the function "followitem()", and send the listing_id from the listing it was clicked on from.
I hope someone can help me!
findAllListings.addEventListener("click", async () => {
let maxPriceInput = document.getElementById("price");
let maxPrice = maxPriceInput.value;
let maxDateInput = document.getElementById("date");
let maxDate = maxDateInput.value;
let locationInput = document.getElementById("location");
let location = locationInput.value;
let usedNewInput = document.getElementById("usedNew");
let usedNew = usedNewInput.value;
let data = {
maxPrice,
maxDate,
location,
usedNew,
};
table.innerHTML = "";
table.innerHTML += `
<tr>
<th>picture</th>
<th>name</th>
<th>category</th>
<th>price</th>
<th>location</th>
<th>used</th>
</tr>
`;
await fetch("http://localhost:4000/allListings", {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((res) => res.json())
.then((res) => {
console.log(data);
for (const key in res) {
if (output == res[key].category) {
table.innerHTML += `
<tr>
<td><img src="${res[key].picture}" style="height:200px;width:auto;"/></th>
<td>${res[key].name}</th>
<td>${res[key].category}</th>
<td>${res[key].price}</th>
<td>${res[key].location}</th>
<td>${res[key].usedNew}</th>
<td><button onclick="${followItem(res[key].listing_id)}">Follow</button></td>
</tr>
`;
}
}
})
.catch((error) => {
console.log(error);
});
});
function followItem(listing) {
console.log(listing);
let userId = localStorage.getItem("loggedInUser");
let data = {
userId: userId,
listingid: listing,
};
fetch("http://localhost:4000/allListings/follow", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((data) => {
if (data.msg === true) {
window.alert("you are now following this item");
window.location = "./allListings.html";
} else if (data.msg === false) {
window.alert("Error, please try again");
}
})
.catch((error) => {
console.log(error);
});
}

Nuxt:Vuex update data from button click not working. error "Cannot read property 'results' of undefined"

I've using the store to update data in a pages file. The really strange thing is the data sometimes appears if i add/remove "results" from state.mbbalance.results
If I add .results I get an error.
Cannot read property 'results' of undefined
If I remove the .results and leave as state.mbbalance ,click the button
I can see the data networks tab in browser as a valid response. But the data won't display on webpage.
results: [{id: 7, balance: 30, exposure: 0, free_funds: 30},…]
I'm not sure why I get the error as the code should work as expected and display a list of balances from the backend. Can anyone tell me why the data won't update?
versions
"nuxt": "2.15.7",
"#nuxtjs/axios": "^5.13.6",
This is my store.
store/index.js
export default {
state: () => ({
loggedIn: false,
user: null
}),
actions: {
async nuxtServerInit ({ commit }, { req, app }) {
console.log('nuxtServerInit', req.session.authToken)
if (req.session.authToken) {
const data = await app.$axios.$get('/api/auth/me/')
commit('SET_USER', data)
} else {
commit('SET_USER', null)
}
},
async login ({ commit }, creds) {
await this.$axios.$post('/auth/login/', creds)
const data = await this.$axios.$get('/api/auth/me/')
commit('SET_USER', data)
},
logout ({ commit }) {
this.$axios.$post('/auth/logout/')
commit('SET_USER', null)
},
async getMBalance(context) {
const res = await this.$axios.get('api/balance/')
if (!res.error) {
context.commit("SET_MB_BALANCE", res.data)
} else {
context.commit("SET_MB_BALANCE", [])
}
}
}
}
pages/balance.vue
<template>
<div id="app">
<button class="btn btn-primary" #click.prevent="updateItem">get</button>
<table>
<thead class="thead-dark">
<tr>
<th>Balance</th>
</tr>
</thead>
<tbody>
<tr v-for="o in mbbaldata" :key="o.id">
<td>{{o.balance}}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import { mapMutations, mapState } from 'vuex';
export default {
computed: {
...mapState({
mbbaldata: (state) => state.mbbalance.results,
})
},
methods: {
updateItem() {
this.mb_balance = this.$store.dispatch('getMBalance')
}
}
}
</script>

Unable to display the results from my returned array using axios and vue

I have tried to follow the guidance I have already received but I am encountering the following issue:
I have no errors in the console or terminal, but nothing is displayed even when I know I have an array of data.
My updated code is as follows, I am sure I have followed the guidance kindly provided.
HTML:
<tr v-if="myuser" v-for="myuser in allMyUsers" :key="">
<td>{{ myuser.email }}</td>
<td></td>
</tr>
SCRIPT:
<script>
import axios from 'axios';
export default {
computed: {
allMyUsers () {
return !this.$store.getters.myuser ? false : this.$store.getters.myuser
},
},
created () {
this.$store.dispatch('allMyUsers')
}
}
</script>
GETTER:
myuser (state) {
return state.myuser
},
Function:
allMyUsers ({commit, state}) {
if (!state.idToken) {
return
}
globalAxios.get('/users.json' + '?auth=' + state.idToken)
.then(res => {
const data = res.data
const myusers = []
for (let key in data) {
const myuser = data[key]
myuser.id = key
myusers.push(myuser)
}
commit('storemyuser', myusers)
})
.catch(error => console.log(error))
}
And finally my MUTATION:
storemyuser (state, myuser) {
state.myuser = myuser
},
Thank you again for your assistance, you guys really are great at helping newbies like me learn.
I should add that I know from the console my function is returning the data I expect

How to populate a Vuetify DataTable with axios

i don't know why my tables are not populated with axios, this is my DataTable template, like the documentation:
<v-data-table
:headers="headers"
:items="items"
hide-actions
class="slideInDown"
>
<template slot="items" slot-scope="props">
<td>{{ props.item.nombre }}</td>
<td class="text-xs-right">{{ props.item.calle }}</td>
<td class="text-xs-right">{{ props.item.numExterior }}</td>
<td class="text-xs-right">{{ props.item.numInterior }}</td>
<td class="text-xs-right">{{ props.item.codigoPostal }}</td>
</template>
</v-data-table>
And this is my script:
<script>
export default {
data () {
return {
items: [
{
nombre: "",
calle: "",
numExterior: "",
numInterior:"",
codigoPostal: "",
}
],
}
},
methods:{
}
created(){
axios.get('http://localhost:58209/api/GetEstaciones',
{
headers:
{
"Authorization": "Bearer "+localStorage.getItem('token')
}
}).then(response => {
this.items = response.data;
}).catch(error => {
console.log(error.response)
});
},
mounted(){
let token = localStorage.getItem('token');
if(token == null){
this.$router.push('/');
}
},
}
</script>
But the table is not populated, and when i debugging my WebAPI in Visual Studio it's working the Get method even with Postman. In my script i omit the heders[], i only show the items.
In Postman shows like this:
"calle": "AVENIDA BLA",
"numExterior": 121,
"numInterior": 2,
"codigoPostal": 123456,
"nombre": "ASDFGGHJKL"
You have to use the mounted :
chk the source code of this page ( click on ok with login you with the default demo account ... )
this example has the additional logic for server side paging and replacing the url params to the back-end , but it might help you grasp the events flow better ...
Short answer ( no error handling, no paging etc. ) :
const vm = new Vue({
el: '#app',
data: {
monthly_issues: []
},
mounted() {
// this is the url of the back-end spitting out json
axios.get("/tst_issue_tracker/select/monthly_issues")
.then(response => {this.monthly_issues = response.data.dat
})
}
})
Long answer:
mounted() {
var url_params = {}
if( window.location.toString().indexOf("?") != -1) {
window.location.search.split('?')[1].replace(/([^=&]+)=([^&]*)/g, function(m, key, value) {
url_params[decodeURIComponent(key)] = decodeURIComponent(value);
});
} else {
url_params = { as:"lbls" };
}
this.UrlParams = url_params;
axios.get((window.location.pathname).replace("/list/" , "/select/") , { params: url_params } )
.then(response => {
this.gridData = response.data.dat ;
this.pageSize = url_params['page-size'] || 10 ;
this.pageNum = url_params['page-num'] || 1 ;
var totalRSsize = response.data.met ;
var remainder = totalRSsize % this.pageSize
var toAdd = 1 // page-size 10 , total-rs-size 30 => 3 and not 4
if ( remainder == 0 ) { toAdd = 0 }
this.pagesCount = Math.floor(totalRSsize/this.pageSize ) + toAdd
})
.catch(function(error) {
document.getElementById("div_msg").innerHTML="<span id=\"spn_err_msg\">" + error.response.data.msg + '</span>'
})
}

Property or method "filterQuery" is not defined on the instance but referenced during render

My Html code part is here:
<input v-model="filterQuery" placeholder="Filter rules" class="form-control">
<table v-if="filteredUsers.length">
<tbody is="transition-group" name="user-list">
<tr v-for="user in filteredUsers" :key="user.id">
<td v-for="(column,index) in tableColumns">
<div class="rules">
{{ getField(user, column.field) }}
</div>
</td>
</tr>
</tbody>
</table>
<p v-if="statusMessage" class="well">
{{ statusMessage }}
</p>
And my Script part is:
export default ({
data: {
tableColumns: [{
field: 'name'
}],
rules: [],
filterQuery: '',
orderByField: 'name',
fetchError: false
},
created: function () {
this.fetchUsers()
},
methods: {
fetchUsers: function () {
var vm = this
vm.rules = []
vm.fetchError = false
fetch('http://172.26.3.44:8002/orientDbRestAPI/rules').then(function (response) {
return response.json()
}).then(function (rules) {
vm.rules = rules.result
}).catch(function () {
vm.fetchError = true
})
},
getField: function (object, field) {
return _.at(object, field)[0]
}
},
computed: {
filteredUsers: function () {
var vm = this
return _.orderBy(vm.rules.filter(function (user) {
var regex = new RegExp(vm.filterQuery, 'i')
console.log('>>>> ' + user.name + ' -- ' + vm.filterQuery)
return (regex.test(user.name))
}), vm.orderByField)
},
statusMessage: function () {
if (this.fetchError) {
return 'There was a problem fetching the rules. JSONPlaceholder might be down.'
}
if (this.rules.length) {
if (!this.filteredUsers.length) {
return 'Sorry, no matching rules were found.'
}
}
else {
return 'Loading...'
}
}
})
With the above code, the error below occurs when the button is clicked.
vue.runtime.esm.js?a427:430 [Vue warn]: Property or method
"filterQuery" is not defined on the instance but referenced during
render. Make sure to declare reactive data properties in the data
option.
In your template you use filterQuery but you haven't declare it in the data or the computed properties of your instance. You should define it like that:
export default ({
data: {
filterQuery: '',
// ...
},
// ...
})