ProxyTable doen't work in vuejs when call api - api

In config/index.js i config like this
proxyTable: {
'/api': {
target: 'http://localhost:44322',
changeOrigin: true
}
},
And this code i call get method.
<template>
<div>
<ul v-if="posts && posts.length">
<li v-for="post of posts" v-bind:key="post.employeeId">
<p><strong>{{post.firstName}}</strong></p>
<p>{{post.lastName}}</p>
<p>{{post.phoneNumber}}</p>
<p>{{post.dateOfBirth}}</p>
<p>{{post.email}}</p>
</li>
</ul>
<ul v-if="errors && errors.length">
<li v-for="error of errors" v-bind:key="error.id">
{{error.message}}
</li>
</ul>
</div>
</template>
<script>
import Axios from 'axios'
export default {
name: 'Axios',
data () {
return {
posts: [],
errors: []
}
},
// Fetches posts when the component is created.
created () {
Axios.get('/api/employee')
.then(response => {
// JSON responses are automatically parsed.
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
console.log(e)
})
}
}
</script>
I want when i call
http://localhost:8080/#/axios
the client call to backend :
http://localhost:44322/api/employee
But nothing happen, i see in header of request the url is :
localhost:8080
i do flow the link of vuejs: https://vuejs-templates.github.io/webpack/proxy.html ,part API Proxying During Development. Any idea for this?
Thanks!!

you would see the request url as http://localhost:8080/api/employee in the browser
and finally the request will be transferd to http://localhost: 44322/api/employee which you won't see in network panel of your browser

Related

Losing my data when i refresh page in vuejs

I'm creating a social network for project in my formation, i have a like system and it work.
i have a components cardArticle with all info and i try to do a like count. It work but when i refresh the page or going on other page, i lost all my data likes (my data is not saved)
components/CardArticle.vue
<template>
<div id="card">
<div>
<a class="cardLink">
<img class="card-img" v-if="post.imageUrl !== undefined" :src="post.imageUrl" />
<h2 class="cardTitle"> {{ post.title }}</h2>
<p class="cardDescription"> {{ post.description }}</p>
</a>
</div>
<div class="buttonIcon">
<div>
<button type="button" class="buttonDelete" id="buttonDelete" #click="deletePost"
v-if="this.post.userId === this.user.userId || this.user.isAdmin === true">Supprimer</button>
<button type="button" class="buttonEdit" id="buttonEdit" #click="modifyPost"
v-if="this.post.userId === this.user.userId || this.user.isAdmin === true">
Editer
</button>
</div>
<div class="divIconLike">
<div class="iconLike">
<a #click="sendLike">
<i class="fa-regular fa-thumbs-up"></i>
</a>
</div>
<div class="countLike">
<p> {{ likes }} </p>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
import router from "../router/index.js";
export default {
name: 'CardArticle',
data () {
return {
likes: 0
}
},
props: {
post: {
type: Object
}
},
computed: {
user() {
return this.$store.getters.user;
}
},
methods: {
sendLike() {
axios.post("http://localhost:3000/api/articles/" + this.post._id + "/like", {
userId: this.user.userId
}, {
headers: {
Authorization: "Bearer " + this.user.token
}
})
.then(response => this.likes = response.data.article.likes)
.catch(error => console.log(error))
}
}
}
</script>
views/home.vue
<template>
<div class="home" v-if="this.user.token !== null">
<CardArticle v-for="post in allPosts" v-bind:key="post.id" :post="post" />
</div>
</template>
<script>
import CardArticle from "../components/CardArticle.vue"
import axios from "axios";
export default {
name: 'HomeArticle',
data () {
return {
post: {
title: "",
description: "",
imageUrl: ""
},
allPosts: [],
}
},
computed: {
user() {
return this.$store.getters.user;
}
},
components: {
CardArticle,
},
mounted() {
axios.get("http://localhost:3000/api/articles", {
headers: {
Authorization: "Bearer " + this.user.token
}
})
.then(response => {
this.allPosts = response.data;
})
.catch(error => {
return error;
})
}
}
</script>
What i should do for not losing my data ?
I would not use vuex or localstorage for that if possible, you have idea ?
Thanks for your help
If you loading data from server, then refresh page, you always will be lose data, because browser loading page again from server, and application will load data again.
If you don't want use vuex (but why not?), you can write data to cookies (by setting cookie value), then load it on app startup (when page is loaded). But it's not best practice at all. You can use vue3-cookies lib (link).
By the way, better learn to use stores, most progressive, I think, is Pinia.
Check: https://pinia.vuejs.org/
i lost all my data likes (my data is not saved)
likes is belong to each articles and It should have been saved to your db and call API to retrieve it again on component mounting:
export default {
name: 'CardArticle',
data () {
return {
likes: 0 // It's not managed by component state
}
},
methods: {
sendLike() {
axios.post("http://localhost:3000/api/articles/" + this.post._id + "/like", {
userId: this.user.userId
}, {
headers: {
Authorization: "Bearer " + this.user.token
}
})
.then(
// invalidates, update allPosts props (emit to parent)
)
.catch(error => console.log(error))
}
}
}

Rendering component on runtime after Http request in VueJS

I'm trying to conditionally render a component in VueJS after an Http request right away when the application starts. If the response is ok I would like to render component 1, otherwise component 2. I would also like to render the component onClick
App.vue
<template>
<div id="app">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="navbar-collapse" id="navbarsExample05">
<ul class="navbar-nav pl-md-5 ml-auto">
<li v-for="tab in tabs" v-bind:key="tab" v-bind:class="['nav-item nav-link', { active: currentTab === tab }]"
v-on:click="currentTab = tab">
{{ tab }}
</li>
</ul>
</div>
</nav>
<component v-bind:is="currentTabComponent" class="tab"></component>
</div>
</template>
<script>
import Comp1 from '../components/comp1'
import Comp2 from '../components/comp2'
export default {
name: 'App',
components: {
Comp1,
Comp2
},
data: function() {
return {
currentTab: 'Comp2',
tabs: ['Comp1', 'Comp2']
};
},
computed:{
currentTabComponent: function () {
function check(){
fetch('someHttpUrl')
.then(response => response.json())
.then(data => {
resolve('Comp1')
});
.catch(err => {
resolve('Comp2')
})
}
var result = check();
result.then(async function (data) {
return data
})
}
}
}
</script>
When I click on the tab, the right component is loaded. But not when the application starts.
Is there any Vue method to render asynchronous a component?
There is no need to have currentTabComponent computed method.
You can just make your HTTP call and update currentTab when it is done.
Something like this:
mounted() {
fetch('someHttpUrl')
.then(response => response.json())
.then(data => {
this.currentTab = 'Comp1'
});
.catch(err => {
this.currentTab = 'Comp2'
})
}
I also removed the method named check as it seemed redundant.

Why does axios delete not work as I want, how to fix it?

I took the data from https://jsonplaceholder.typicode.com/posts, I got it out normally, but I also want to create a button when I click on it, the post will be deleted. I wrote the code, but it does not work, can you tell me what is the error? When you click on the button in the console writes 'delete', but the post remains.
Screenshot of console
<template>
<div id="app">
<ul>
<li v-for="post of posts">
<p>{{ post.title }}</p>
<p>{{ post.body }}</p>
<button #click="deleteData(post._id)">Delete</button>
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'app',
data () {
return{
posts: [],
}
},
created(){
axios.get('http://jsonplaceholder.typicode.com/posts').then(response => {
this.posts = response.data
})
},
methods: {
deleteData(_id) {
axios.delete('http://jsonplaceholder.typicode.com/posts/' + id)
.then(response => {
console.log('delete')
this.posts.splice(
this.posts.findIndex(e => e.id === id)
)
})
.catch(function(error) {
console.log(error)
})
},
}
}
</script>
Your approach is good, but you're using methods in wrong way.
There are two things you have to remember.
First, your post variable is an array.
API gives you json data, and what you have to do is to push that data into your array, instead of using = operand
Secondly, splice(index) just returns the same object.
Using splice(index, 1) instead.
It will delete 1 post from that index.

server side rendering problem with vuejs cli 3

I am working on a vuejs app , and I am trying to use server side rendering, but I am having a problem with the rendering, but I am having this error when I start my server.
[HPM] Error occurred while trying to proxy request /main.js from localhost:8080 to http://localhost:8081 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)
I can see the content of server page localhost:8080, but the client page in localhost:8081 cannot be reached.
I am using this code in Github I am testing with this vue component:
import axios from 'axios';
export default {
name: 'Blog',
data () {
return {
blog: null,
error: null
}
},
beforeCreate: function() {
axios({ method: "GET", "url": "path to api" }).then(result => {
this.blog = result.data.blogs[0];
},
error => {
this.error = error;
});
},
mounted () {
axios({ method: "GET", "url": "path to api" }).then(result => {
this.blog = result.data.blogs[0];
},
error => {
this.error = error;
});
}
}
<template>
<div class="Blog">
<section>
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="page-title">
<div class="row">
<div class="col-md-9 col-xs-12">
<h2><span>{{ blog.title }}</span></h2>
<!-- Other data here! -->
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
</template>
for the server page, I just can see some css but I cannot see the data that I get from axios! But I see that the blog property contains the data, it's just not displayed in the page. Any help would be very appreciated.

Api route returning empty array

Api route returning empty array evenif table contains data.
I want to list the users.Route model binding fails
This is my api route
Route::middleware('auth:api')->get('/users',function(){
return App\User::get();
});
This is my vue component used in the blade template
<template>
<div class="row" style="min-height:250px;">
<ul>
<li v-for="user in users">
#{{user.name}}
</li>
</ul>
</div>
</template>
<script>
export default{
data() {
return {
users : [],
}
},
ready: function(){
this.getUsers();
},
methods: {
getUsers: function(response){
axios.get('http://localhost:8000/api/users')
.then(response => {
this.users = response.data;
})
.catch(error => {
});
},
},
}
</script>